Questions tagged [django-models]
9299 questions
1
votes
2
answer
1.2k
Views
DRF Object of type 'User' is not JSON serializable
I'm trying to return the details of the current logged in user in the following way:
from .serializers import UserSerializer
class UserDetailsView(RetrieveAPIView):...
1
votes
2
answer
46
Views
Django Model: Find Avg by Grouping from models
I have been trying to find the avg for rating a get queryset.
This is my models.py
class Movie(models.Model):
title = models.CharField(max_length=240)
release = models.DateField(blank=True)
review = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
poster = models.FileFiel...
0
votes
0
answer
6
Views
Django no such table after migrations
After trying all sort of migration im still getting this error
I only get this error when trying to save the new object
Traceback (most recent call last):
File '', line 1, in
File 'C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py', line 741, in save...
1
votes
2
answer
31
Views
Django Registering two different types of users with different fields
I want to create two users: patient and doctor. Both users will share some of the standard fields like first_name, last_name, etc. However, they should have different fields. Only the doctor, for example, will have fields like expertise and days_available.
I reviewed a similar question but it doesn'...
1
votes
2
answer
40
Views
is there a way to override model methods in django?
I have a model like this:
class Car(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
create_date = models.DateTimeField('date added', auto_now_add=True)
modify_date = models.DateTimeField('date modified', auto_now=True)
...
def last_tracked_location(self):
...
try:
url = '...
1
votes
1
answer
29
Views
How to limit the number of items displayed in Django app
I have this Django model in my newspaper app:
class Article(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
def __str__(self):
return self.title...
1
votes
2
answer
32
Views
How to filter foreign key objects in django queries?
I have two models, one related to other by foreign key like this
class CapturedPrescriptionModel(ColModel):
p_id = models.IntegerField()
p_age = models.IntegerField()
p_gender = models.CharField(max_length=10)
p_care_type = models.CharField(max_length=100)
bacteria_id = models.ForeignKey(BacteriaLis...
1
votes
1
answer
41
Views
How to pass two different arguments in a single function in django?
Python newbie here, I am trying to create a web-app where shippers can post their truck-loads on sale and accept bids from transporters, and the transporters can post their bids on loads.
I have a list view function in my views.py, where a shipper can see all the bids posted by different suppliers,...
1
votes
3
answer
4.4k
Views
Set attribute of a model to a certain value before saving
I have this:
class OrderForm(ModelForm):
class Meta:
model = Order
exclude = ('number',)
def __init__(self, *args, **kwargs):
super(OrderForm, self).__init__(*args, **kwargs)
if self.initial.get('account', None):
self.fields['customer'].queryset = Customer.objects.filter(account=self.initial.get('ac...
0
votes
0
answer
6
Views
Python - Django 1.5 Is there a possible workaround to fix database error
Im working a school management project and I integrated a forum app. It now pushes a database error even after I migrated / synced the database. Are there possible workarounds?
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/forums/category/add/
Django Version: 1.5.12
Excepti...
1
votes
1
answer
18
Views
Django: Can I check if a model instance matches a filter without filtering all model instances
I have an instance of a model. I have a queryset. Can I check if the instance matches a filter without filtering all model objects?
Situation:
I have a model Alpha, when this model is created I need to check if it matches a user defined filter which is stored in model Bravo. There will be many Alpha...
1
votes
0
answer
8
Views
Django model limit choices based on another model but with a specific field value
I have got 2 models, simplified for this question. In the Article model, how can I limit the choices= of the field Article.status based on the entries in the Category model which have a specific Category.type value?
class Article(models.Model):
name = models.CharField(max_length=100)
# Set choices=...
1
votes
1
answer
151
Views
Populate a Django Model from List of Lists
I have a list of lists. I'd like to populate a Model with that data.
my_list = [['January', 'February', 'March'], [10, 20, 30], [2, 4, 6]]
The Model I's like to build is:
MyModel(models.Model):
month = models.Charfield(maxlength=12) # This is my_list[0]
sales = models.DecimalField() # This is my_lis...
0
votes
0
answer
3
Views
Django Content-Types Foreign Key Contraint Failure
For the sake of dynamic forms that can accept different data-types, I am attempting to use Django Content-types to create a relation between a field in the form and the data stored within (i.e. linking an instance of the formfield model to an model that consists solely of an integer). I have followe...
1
votes
2
answer
681
Views
Django: List Products of each Categories in a page
I have a few categories and I would like to list the products per category in the format below (categories is an FK to products):
Category 1
bunch of products
....
Category N
bunch of products
I have tried many ways but so far I only get the categories but not the products to show in my HTML.
model...
1
votes
2
answer
32
Views
Django Query: How to find all posts from people you follow
I'm currently building a website with the Django Framework. I want on the homepage of my website to display all posts made by people the user is following. Here are the classes for Profile, Story and Follow:
class Profile(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
fi...
1
votes
2
answer
89
Views
Migrate a PositiveIntegerField to a FloatField
I have an existing populated database and would like to convert a PositiveIntegerField into a FloatField. I am considering simply doing a migration:
migrations.AlterField(
model_name='mymodel',
name='field_to_convert',
field=models.FloatField(
blank=True,
help_text='my helpful text',
null=True),
),...
1
votes
1
answer
33
Views
Find models that have only one particular related model
Consider the following models:
class Product(models.Model):
name = models.CharField(max_length=...)
class Size(models.Model):
name = models.CharField(max_length=...)
products = models.ManyToManyField(Product, through=ProductXSize,
related_name='sizes', related_query_name='size')
class ProductXSize(m...
1
votes
1
answer
50
Views
What is the usage of `FilteredRelation()` objects in Django ORM (Django 2.X)?
I've seen Django 2.0 consists of FilteredRelation object in queryset. What is the usage of newly introduced FilteredRelation?
What I've looked into?
I observed Django 2.0 Documentation but I could not understand idea behind this FilteredRelation object.
I looked into following code. But I didn't get...
1
votes
2
answer
27
Views
Django how to get the users who are not in many2many field?
'models.py'
class StaffProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')
staff_user = models.ManyToManyField(User, null=True, blank=True, related_name='staff_user')
mobile_number = models.CharField(max_length=14, validators=[RegexValidato...
1
votes
0
answer
24
Views
Print Dates range if they are available in db
from below code i am going to print date ranges that's fine but what the problem is i need to print the date ranges , those available in database only [this image shows the created_at date field which is in look model . I need these dated to be printed if user select the date rage between dec 1 to...
1
votes
1
answer
68
Views
Super easy tutorial throwing django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I created a simple django web app. When I run the models.py file I get the following error. I've tried a number of solutions including taking out my apps one by one, reinstalling django (I have version 2.0) doing an 'ol system restart, inserting import django + django.setup(), refreshing the virtual...
1
votes
1
answer
29
Views
Remove data from the database when the remove button of a datatable is clicked
I am using a datatable to dispay information for the user and it is generated a delete button per row.
I would like to delete the row data from the database when the user click on it.
How can I do that?
HTML
...
$('#id_data').DataTable({
destroy: true,
data:data_array_data,
'bLengthChange': false,
/...
1
votes
1
answer
58
Views
How can I get the current user's group in forms.py in Django?
I have a scenario where i need to pass the logged-in user's groud name and get the list users in that group.
forms.py -- in the below code i need to pass the user's group instead of Banglore
class UpateTaskMaster(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UpateTaskMaster, self).__i...
1
votes
2
answer
166
Views
I am having errors with Django authenticated built-in function
I have been woking in django for a while. Now i am facing some problems with built-in function in django. The error state that TypeError: 'bool' object is not callable. This kind of error happened because of statement 'print(request.user.is_authenticated())'.
Here below is source code:
def login_pa...
1
votes
1
answer
279
Views
DJango-tables2 how do I refresh/update the table on the webpage without hitting refresh button
I followed the DJango-tables2 official tutorial and was able to create data set in the terminal using:
Person.objects.bulk_create([Person(name='Jieter'), Person(name='Bradley')])
However, the new data in the table on the website doesn't show up until I hit the refresh button. My question is how the...
1
votes
2
answer
101
Views
Django Model serving Media Files
I have two models: Packages and Images. Images has many to one relation with Packages. Images table has a foreign key package_id. I have to display the attributes country, price of Packages with one image related to the package. There can be many images related to a single package however, I have to...
1
votes
0
answer
60
Views
Django Model Design (Big model vs multiple)
I have a question about designing my models. Suppose I have a following model:
class Comment(models.Model):
who = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=1000)
likes = models.IntegerField(default=0)
parent...
1
votes
0
answer
36
Views
How to join two different ORM query to return them as one JSON object
I have been trying to output get result of both author name and book name is the same json dict, I got the all the books written by an author but I want author name before books too and here is the relevant code:
Models
class Books(models.Model):
bid = models.BigIntegerField(primary_key=True)
bname...
1
votes
0
answer
94
Views
how to handle mongoengine field name with “-”dash in django models.py
class Patent_document(EmbeddedDocument):
meta = {'collection': 'patent', 'strict': False}
ucid = StringField(required=True)
abstract = EmbeddedDocumentField(Abstract)
description = EmbeddedDocumentField(Description)
bibliographic-data = EmbeddedDocumentField(Bibliographic_data)
My json file in Mongo...
1
votes
1
answer
268
Views
Add A New Field To Existing Model - django.db.utils.ProgrammingError: column {field} does not exist
models.py
I have a Scorecard model that has a ManyToManyField to another model named Account:
class Scorecard(models.Model):
....
name = models.CharField(max_length=100)
accounts = models.ManyToManyField(Account)
...
def __str__(self):
return self.name
My Account class currently has four fields (acc...
1
votes
0
answer
26
Views
Django model field _('name')?
I'm reading the django.contrib.auth.models.py file and I see this being done all over the place:
name = models.CharField(_('name'), max_length=255)
I believe 'name' is the option designating the name of the database column to use for this field. But what does surrounding it with _('...') mean? And...
1
votes
0
answer
245
Views
Using multiselect widget for a ForeignKey field Django
Good day i seem to be lost in how i want to implement something. so here is how it goes
ive got a carowner model
class carowner(models.Model):
.....
carowner = models.CharField(primary_key=True)
and a cars model
class car(models.Model):
....
carowner_id = models.ForeignKey(carowner)
it has a forei...
1
votes
0
answer
148
Views
“AnonymousUser” Error When Non-Admin Users Log In - Django
When I try to login users registered through my AbstractBaseUser model I get the error:
'AnonymousUser' object has no attribute '_meta'
Which highlights the code:
login(request, user)
However, if the user is an admin there is no problem, leaving me to believe that the problem isn't with the 'login_...
1
votes
1
answer
157
Views
Django Multiple Record Insert CreateView ( not enough values to unpack (expected 2, got 1))
i am getting the following message while saving the record. not enough values to unpack (expected 2, got 1)
I am getting a Acquisition ID and attaching qoutations(single or multiple ) and once saving the record the system pops out the error.
there is no error if i select the ACQID from createview...
1
votes
1
answer
88
Views
In what cases should I use UUID as primary key in Django models
What are advantages and disadvantages of UUID field?
When should I use it as a primary key? When should I use default primary key?
My table has many rows. Is it possible that max value of default primary key will be exceeded?
I use PostgreSQL.
1
votes
0
answer
30
Views
Django app: on modelse.py any kind of def is not working
here my code, last two function is not working i am also trying more function but still they are not working.
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = model...
1
votes
0
answer
37
Views
How to prefetch multiple fields by the same queryset
I'm trying to do a Prefetch on my Models
The Models are like so:
Model A
---Field 1
---Field 2
Model B
---Field RR FK to Model A related_name RR
---Field SS FK to Model A related_name SS
I was making a prefetch for my model A and I ended up with something like this
B = B.objects.all()
A = A.prefetch...
1
votes
0
answer
236
Views
How to Upload a text file in django using templateview based view and model based forms
I am new to django and stuck on uploading a simple file. I am using TemplateView as views and model based form. I am stuck here. I have no idea what to do. I am using django 2.0. I have attached the code what I have done so far.
setting.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path...
1
votes
1
answer
919
Views
How to resolve FOREIGN KEY constraint failed
I am following a tutorial on a basic concept. How to customize a user in django.
I don't want to use the built in auth user. I found this tutorial which seems to work until a point.
I get through the whole tutorial with everything working. however when I run my project, log in and open the user in t...