FAQ Database Discussion Community


How to save the value of a jQuery sliderbar into a Person model?

jquery,django,django-models,django-forms,django-views
I am trying to save the value of an jQuery element I added to my SurveyWizardForm into my class Person(models.Model): and therefore my database. All of the other elements in my form were created the normal way, by creating the necessary fields and widgets in my forms.py and the data...

django - What are the alternatives to having a ForeignKey to an abstract class?

python,django,django-models
I want to have an abstract Company model in Django, and extend it depending on the type of the company involved: class Company(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) class Meta: abstract = True class Buyer(Company): # Buyer fields.. pass class Seller(Company): # Seller fields... pass Every user on the...

Record Total Value in Django

django,django-models
Record the value of a calculated field is really more efficient to calculate without saving? class SaleDetail(models.Model): product = models.ForeignKey(Product) quantity = models.IntegerField() price = models.DecimalField(max_digits=8, decimal_places=2) subtotal = models.DecimalField(max_digits=8, decimal_places=2) def save(self, *args, **kwargs): self.subtotal = self.price * self.quantity super(SaleDetail, self).save(*args, **kwargs) Calculated field class SaleDetail(models.Model): product = models.ForeignKey(Product)...

Send email django from any host

python,django,email,django-models
I have read plenty of links for sending emails through django. I've tried all of them but they don't work. I tried sending an email through the python shell and I get '1'. - So what are the settings that I should use for the email to work, I'm willing...

InlineModelAdmin not showing up on admin page

django,django-models,django-admin
I have from django.db import models from django.contrib import admin # Create your models here. class Author(models.Model): name = models.CharField(max_length=10) class Book(models.Model): author = models.ForeignKey(Author, null=True, blank=True) title = models.CharField(max_length=10) class BookInline(admin.TabularInline): model = Book class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, ] registered on my admin page, however books are...

Continuously add new entries to Django model

django,django-models
I need some conceptual help understanding how this idea would work. If I have a user make a list and they can add infinite items to each list, how would I want to map out the model? In my list model I have user = ForeignKey(User), so each instantiation of...

Is there a way to see the raw SQL executed by a bulk_create on django?

python,django,postgresql,django-models,django-1.8
I'm using Django's ORM to insert thousands of objects in a Postgre's DB. And it works fine, but sometimes one of those registers have a wrong format and the insert operation doesn't work. I can't do this kind of insert ignoring errors so I'd like to see the SQL executed...

Django 1.8: How use Model from different application?

python,django,django-models,django-1.8
My problem is I want to create something like common-application (this can be also a standard Python Module) with e.g.: Model_1 Model_2 Model_3 And also create application_1 and application_2 where models from common-application being used by this e.g.: application_1 Model_1 Model_2 Model_4 - app specific additional model application_2 Model_1 Model_2...

Django filter a many-to-many list of IDs

django,django-models
I'm trying to filter a many-to-many feild on a model where I'm give a comma separated list of ids in the URL... ids = 3,7 cat_ids = self.request.QUERY_PARAMS.get('cat_ids', None) super(Filter, self).get_queryset(*args,**kwargs).filter(categories__id_in=cat_ids) Error: TypeError: Related Field got invalid lookup: id_in Is this possible if so how?...

Update queryset attribute value without losing order on that attribute

python,django,django-models
class Foo(models.Model): value = models.IntegerField() class Meta: ordering = ('value',) Consider this queryset: [<Foo pk=1 value: 0>, <Foo pk=3 value: 2>, <Foo pk=2 value: 5>] What would be a good way to update the queryset to look like this: [<Foo pk=1 value: 0>, <Foo pk=3 value: 1>, <Foo pk=2 value:...

Django: Store multiple & dynamically ordered model sequence

python,django,django-models
Lets say, a user has video clips and images, both of them with their corresponding model, VideoClipModel and ImageModel. Now i'm adding a new functionality where a user can combine clips and images to create a "final" video. Now what i need is to create a model where i can...

Return error message to custom form in Django

python,django,forms,django-models,django-forms
The fields in my custom registration form looks something like this: <div class="form-group"> {{ form.email.errors }} label for="{{form.email.id_for_label}}"> <b>Email</b> </label> {{ form.email }} </div> My views.py looks like this: def registration(request): registered = False if request.method == 'POST': form = RegForm(data=request.POST) if form.is_valid(): email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] password...

Saving a model containing a FileField in Django

django,django-models
I have the below model; class AudioFile(models.Model): name = models.CharField(max_length=100, default='') audio_file = models.FileField() uploader = models.ForeignKey(User, default='') def __unicode__(self): return self.name The below form; class AudioFileForm(forms.ModelForm): class Meta: model = AudioFile fields = ['name', 'audio_file'] def clean_audio_file(self): audio = self.cleaned_data.get('audio_file',False) if audio: if audio._size > 5*1024*1024: raise ValidationError("File too...

Django column “name” of relation “django_content_type” does not exist

django,django-models
I keep getting the following error when doing a migration (python manage.py migrate): django.db.utils.ProgrammingError: column "name" of relation "django_content_type" does not exist I've done the following to try and fix it but without success: I've delete all the migrations files for each model deleted all the records in django_migrations run...

Posting data from a form into the database using Django

django,django-models,django-forms
I am trying to have a user input a task from the frontend and have that data instantiate a new model and add this new field in the database associated with their account. I have tried the following; Profile HTML <form id="taskitem_form" method="post" action="/"> {% csrf_token %} {% for hidden...

django: default for non-nullable field

python,django,django-models
I am learning django by doing some tutorials and am currently on ownership in the effective-django tutorial. Unfortunately, the tutorials is written for an older version of django so some things are slightly different. I am running into problems when adding an 'owner' field to my model Contact in models.py:...

Django admin filters on remote field via get_list_filter

django,django-models,django-admin
I have 3 models, linked by FKs in a chain like this: class Customer(models.Model): name = models.CharField(max_length=100) class Order(models.Model): name = models.CharField(max_length=100) customer = models.ForeignKey( 'customer.Customer', on_delete=models.PROTECT) class Task(models.Model): name = models.CharField(max_length=100) order = models.ForeignKey( 'order.Order', on_delete=models.PROTECT) Now, if within my TaskAdmin, I use: list_filter = ('order__customer', ) everything works...

Changing Primary Key in Oracle

oracle,django-models,oracle-sqldeveloper
I'm updating a table that was originally poorly designed. The table currently has a primary key that is the name of the vendor. This serves as a foreign key to many other tables. This has led to issues with the Vendor name initially being entered incorrectly or with typos that...

updating a model attribute in django using form

python,django,django-models
I am trying to update a model field in my django app. the application is such that there are two models, Project and Contractor. and their relation is like each project can assign multiple contractors and each contractor can work on multiple projects..and both project and contractor are associated to...

Django 1.8 model form fields not showing when rendering template

python,html,django,django-models,django-forms
I am trying to create a form which will allow users to input data into my database. I have followed many tutorials which may have lead to my confusion. The problem is that my page is showing up with all the html elements, but the form is not being displayed....

Can't run django project on mac imported from ubuntu

python,django,python-3.x,django-models,virtualenv
My colleague started a django project on Ubuntu. I want to run the same project on OS X Yosemite. We both use python3.4 and following packages: Django (1.8.2) Pillow (2.8.1) pip (7.0.3) setuptools (17.0) wheel (0.24.0) And we both run project in virtual env. When I cloned project, I used...

Django does not render my forms' fields

django,django-models,django-forms,django-templates,django-views
I have this model in models.py: class Life_events(models.Model): patient = models.ForeignKey(Demographic) HSCT_date = models.DateField('HSCT date',null=True,blank=True) HSCT_outcome = models.CharField('HSCT outcome',max_length=100, null=True, blank=True) partaker_in_clinical_trial= models.CharField('Partaker in clinical trial',max_length=200, null=True, blank=True) date_of_input= models.DateField(null=True,blank=True) def __str__(self): return str(self.patient) My forms.py contains: class LifeEventsForm(forms.Form): def __init__(self,...

django multy level query in foreignkey relationship

django,django-models
How can I do multy level query? My Model is from django.db import models class Subjects(models.Model): name=models.CharField(max_length=20) pub_date= models.DateTimeField(auto_now=True) def __str__(self): return self.name class Question(models.Model): subject = models.ForeignKey(Subjects) ques = models.CharField(max_length=100) pub_date=models.DateTimeField(auto_now=True) def __str__(self): return self.ques class Answer(models.Model): question = models.ForeignKey(Question) ans1 = models.CharField(max_length=50) ans2 =...

Move models between Django (1.8) apps with required ForeignKey references

python,database,django-models,schema-migration
This is an extension to this question: How to move a model between two Django apps (Django 1.7) I need to move a bunch of models from old_app to new_app. The best answer seems to be Ozan's, but with required foreign key references, things are bit trickier. @halfnibble presents a...

Callable in model field not called upon adding new object through Django admin

django,django-models,django-admin
In https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.Field.default we read that the callable of a default field value is called, every time a new object is created. In my model I have: when_first_upload = models.DateTimeField(default=datetime.datetime.now()) When in the admin page I create a new object I always get the same datetime, as if the callable is...

Properly use 'next' paramater in URL, Django

python,django,python-2.7,redirect,django-models
Python/Django newbie here. I am using decorator @login_required(login_url='/login/') to 3 different views. I have multiple such views(think services that website offer) which can be accessed only if you are logged in. When I click on service button, the URL formed is something like this: domain/login/?next=/<service_name>/ How do I use the...

Django 1.8 conditional annotation results in INNER JOIN instead of LEFT OUTER JOIN

django,django-models,django-queryset,django-orm,django-1.8
The models: class Bar(GenericModel): ... class Foo(GenericModel): bar = models.ForeignKey(Bar, related_name='foo_bar') The query: bars = Bar.objects .prefetch_related('foo_bar') .annotate(sum_foo=Sum( Case( When(foo_bar__is_deleted=False, then='foo_bar__amount'), default=Value(0), output_field=IntegerField() ) ) ) The former results in an inner join: SELECT ... FROM "bar" INNER JOIN "foo" ON ( "bar"."id" = "foo"."bar_id" ) ... What I intend...

How to reactivate user django

python,django,django-models,django-admin
I'm currently having troubles in setting is_active field from False back to True in Django. I have a custom Account model which is inhereted from AbstractBaseUser and is managed by class AccountManager(BaseUserManager). By default, I override the is_active field to be False. However, when I try to reactivate the field...

Best way to sign-up django project

django,django-models,django-views
I am working on a project about a workshop where you could sign up for it. When you sign up for an project, and you click on the project to go to the detailview you wil see a list of all the people that are currently signed up for that...

DjangoRestFramework ModelSerializer: field-level validation is not working

django,django-models,error-handling,django-rest-framework,django-serializer
This is my serializers.py (I want to create a serializer for the built-in User model): from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) def validate_username(self, username): if not re.search(r'^\w+$', username): #checks if all the characters in username...

Inheritance in Django: child class updates parent with empty fields

python,django,python-3.x,inheritance,django-models
I am creating a UserProfile for every user created with django.contrib.auth by extending the base abstract user and catching the signal when a new user is registered (I prefer having a separate table for the profiles): class UserProfile(auth_models.User): objects = UserProfileManager() organization = models.CharField(max_length=100) country = CountryField() is_verified = models.BooleanField(default=False)...

Get element of table by instance of foreign key.

django,django-models
I have two models in Django: class Blog(models.Model): author = ForeignKey(Author) post = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=100) I need to get the Blog entry by instance of Author: author_one = Author (name ='John') author_one.save() blog_entry = Blog.objects.get(author = author_one) Do I need to add related name to Author...

Django ORM: All items not in table

django,django-models,django-orm
I've got two models: class SchedulerEvent(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) class SchedulerEventReceipt(models.Model): event = models.ForeignKey(SchedulerEvent, unique=True) generated_on = models.DateTimeField() paid_on = models.DateTimeField() I'm trying to figure out how to get a list of all SchedulerEvents that aren't in the SchedulerEventReceipt table for a particular...

How to read csv data into django models?

python,django,csv,django-models
I keep getting this error message after trying to import csv file into Django models. TICKERS has two columns: column[0] = name, column[1] = ticker populate_symbol.py def populate(): with open(TICKERS, 'rU') as csvfile: file = csv.reader(csvfile, delimiter=',') for row in file: add_ticker(str(row[0]), str(row[1])) def add_ticker(name, ticker): c = Symbol.objects.get_or_create(name=name, ticker=ticker)...

django - migrations issue after renaming app

django,django-models
I renamed some django app , and now want to run migrate to update the database. But I get the following error because the old names still are still referenced in the migrations files. ValueError: Lookup failed for model referenced by field pr1.Ticket.project: prod.Project I already tried ./manage.py flush to...

F() Expression strange behavior with Django

python,django,django-models,django-templates,django-template-filters
I have this template tag that ultimately returns a list of 'active' advertisements (checks if Campaign with the active field is True, then pulls ads from the Campaign with a queryset) @register.assignment_tag def get_current_campaigns(amount): # Get all the campaigns that are active current_campaigns = Campaign.objects.filter(active=True) current_campaigns_count = current_campaigns.count() # To...

Modify db object field from .py file in django

python,django,django-models
I have a form that corresponds to Model A available in models.py which has an "amount" field. I also have a Model B which also has a "total_amount" field. When creating a new Model A through it's corresponding form, after form submition I want to save Model A and modify...

Library or API for inferring country/location based on submitted string?

python,django-models,geolocation,input-sanitization
I'm retroactively sanitizing a bunch of data for the Offer Drive product (http://offerletter.io/drive.html). I'm trying to normalize a freeform "location" field to determine if submitted locations fall in the United States (or not). Values may vary in granularity, but all are "real", e.g. San Francisco, CA Milwaukee Bangalore My question...

create_user() takes at least 3 arguments (2 given) Django Social Auth use Costom User Model

django,django-models,django-admin,django-authentication,django-custom-user
i want to make login social auth and i use userprofile to login, but i getting error. This is error: Exception Type: TypeError at /complete/facebook/ Exception Value: create_user() takes at least 3 arguments (2 given) this is my admin.py code class CustomUserCreationForm(UserCreationForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password Confirmation',...

Django's DateTimeField's “auto_now” doesn't seem to work

django,django-models
I have a Comment model. It has following timestamp fields: created = models.DateTimeField(auto_now_add=True, blank=True, null=True) last_edit = models.DateTimeField(auto_now=True, blank=True, null=True) Now when I update a comment using this format: Comment.objects.filter(...).update(text="some new text"), the last_edit field doesn't get updated while the text of the comment does get updated. What's the issue?...

How to translate this raw query to Django ORM

sql,django,django-models,django-templates
I have a model where we have candidates, languages and language Level entities: class Candidate(models.Model): user = models.ForeignKey(MyUser) telephone = models.CharField(max_length=20, unique=True) postcode = models.CharField(max_length=10) class Language(models.Model): name = models.CharField(max_length=50) class LanguageLevel(models.Model): candidate = models.ForeignKey(Candidate) language = models.ForeignKey(Language) level = models.IntegerField(max_length=1, choices=LANGUAGE_LEVEL, default=0) My raw query is: SELECT c.id, COUNT(c.id)...

Django reverse relationship name gives invalid keyword argument error

python,django,django-models
I have the following models: class Catalogue(Base): name = models.CharField(max_length=60) params = models.ForeignKey("Params", related_name="params_item", null=True, blank=True) class Params(Base): name = models.CharField(max_length=60) But when I do this: Params.objects.create(params_item=object_cat, name="Test") I get the error: params_item' is an invalid keyword argument for this function Why can I not use the reverse relation name...

django: ForeignKeyField limit_choices_to “parents pk”?

django,django-models
I've a model (Parent model): class Post(models.Model): image = models.ImageField(upload_to='%Y/%m/%d') title = models.CharField(max_length=200) width = models.DecimalField(max_digits=3, decimal_places=0) height = models.DecimalField(max_digits=3, decimal_places=0) year = models.PositiveIntegerField() def __str__(self): return self.title and another model (Child model): class Addimg(models.Model): post = models.ForeignKey('Post', null=True) addimg = models.ImageField(upload_to='%Y/%m/%d') def __str__(self): return self.post My Addimg Form:...

Django Rest Framework PUT request on unique model field

django,django-models,django-rest-framework,django-serializer
I have the following model class Owner(models.Model): user = models.OneToOneField(User, default=1, editable=True) phone = models.CharField(max_length=40, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) city = models.CharField(max_length=255, null=True, blank=True) state = USStateField(null=True, blank=True) zip = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Device(CreationModificationMixin): _STATUSES = (...

Django form data not submitting/visable in mysql database

django,django-models,django-forms
I designed and built a Django 1.6.2 survey application using a SessionWizardView which is connected to a MySQL database. The problem is that (as far as I can see) the submitted form data is not getting saved to the database. This is my first time building an application like this...

How to use models associated with a user in Django when rendering an HTML page

django,django-models,django-forms
I'm in the learning stages of django. I just dived into a project to learn the framework and am having a series of questions throughout the process. I basically want to have individual pages for users who create a task list and have them post tasks to their own page....

When should I be using null=False on django model fields

django,django-models
These questions ask what the null argument does: differentiate null=True, blank=True in django In Django models.py, what's the difference between default, null, and blank? But I want to know, when should I be using it? For example, why should I ever restrict myself? Is it purely to catch bugs as...

Divide option in django model query

python,django,django-models,django-views
This is my model: class DailyObj(models.Model): RedDate = models.DateField('RecDate') Name= models.CharField(Name,max_length=100,default=None) Total_Rec = models.DecimalField('Total Rec',max_digits=18,decimal_places=2,default=None) top10records = DailyObj.objects.filter(RedDate__gte = fromdate,RedDate__lte = todate,Total_Rec__gt=0).order_by('-Total_Rec')[:10] Here fromdate and todate are variables having proper date values. The above query works fine and returns the records which satisfy the given criteria. However I want each...

Multiple default values specified for column “id” of the table

python,django,database,postgresql,django-models
I use to run my website on my laptop and its database was Sqlite, recently I wanted to transfer it to DigitalOcean and I changed its database to Postgresql, but when I migrate I encounters with some problems. Python 3.4 Django 1.8 Error django.db.utils.ProgrammingError: multiple default values specified for column...

Django models: managing transactions when commit_manually is deprecated

python,django,django-models,override
I'm running Django 1.4.11. I overrode the save() method of a Django model in a way similar to the following code: from django.db import models from django.db import transaction class MyModel(models.Model): # model definition @transaction.commit_manually def save(self, *args, **kwargs): try: super(self.__class__, self).save(*args, **kwargs) foo() # do_other_things except: transaction.rollback() raise else:...

Django Model field calculated from other fields

python,django,django-models,django-admin
There are quite a few other questions here around this but none of them have helped. I would like a yield field to be calculated by yield = starts / finishes fields. I'd like to graph it using Highcharts. However when I add an object via Admin portal - it's...

Django GenericIPAddress field is not validating input

python,django,validation,django-models,django-orm
Hi I have the following Django model class AccessPointIPAddress(models.Model): '''Model for storing AccessPoint IP Addresses.''' ap = models.ForeignKey(AccessPoint, related_name='ip_addresses') ip_address = models.GenericIPAddressField(protocol='IPv4') datetime = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['datetime'] get_latest_by = 'datetime' And I am assuming that django's GenericIPAddressField does some string validation that a string is indeed a...

get call stack for Model Classes in Django

python,django,django-models,models
In Django, I would like to get call stacks of classes in Model; on call, and log them. The Django Model uses QuerySet API to access objects of the Model class. Say, we have defined Model class Abc, and it is called by other django apps using QuerySet API. For...

Django Sorting a List inside a model

python,django,sorting,django-models
I want to keep a list of addresses sorted inside a table. Here is the code for my sorting: (it doesn't work and honestly I have no idea how to go about this I'm new to Django/Python) def detail(request, table_name): table = get_object_or_404(Table, name=table_name) addressSet = table.address_set.all(); addressSet.sort(key=operator.attrgetter('address')) Here is...

Calling methods from models.py inside views.py without creating instance

python,django,django-models,django-1.8
New to Django coming from .NET with an architectural question. Inside my models.py, I have a concept called city. These cities can be enabled/disabled. Inside my views, I want to retrieve all active cities under my view called Cities. I need to retrieve all active cities in many places, so...

Is there any way around saving models that reference each other twice?

django,django-models
My issue is when saving new models that need to reference each other, not just using a related_name lookup, such as this: class Many: owner = models.ForeignKey('One') class One: current = models.OneToOneField('Many') By default, these have null=False and, please correct me if I'm wrong, using these are impossible until I...

How to have 2 Models/Views/Templates on one Page in Django?

python,django,django-models,django-templates,django-views
I know this has probably been asked a 1000 times but I still for the life of me can't find a decent answer. Reading tutorials, Stack and even looking at GitHub for examples - nothing is helping or even guiding me in the right direction. I have 2 separate Models/Views/Templates...

Search a Many to Many Relationship

django,django-models,many-to-many,manytomanyfield
Given a Contributor, I'm trying to find the Registrations the Contributor belongs to. I can't figure out how to traverse the M2M- I need to know which Registrations contain the Contributor in their 'conrtibutor' field...? class Registration(TimeStampedModel): dataset = models.ForeignKey('Dataset', related_name='registration') contributor = models.ManyToManyField('Contributor', related_name='registrations') # many contributors may be...

Django custom form not rendering

python,html,django,forms,django-models
Total newbie here. I am creating a custom registration form for my homepage. I did following: Create formreg.py class RegForm(forms.Form): email = forms.EmailField() password=forms.PasswordInput() password2=forms.PasswordInput() phone= forms.CharField(max_length=10) In Index.html(where the form is), I wrote following inside form tag: <div class="form-group"> {{ form.email.errors }} <label for="{{form.email.id_for_label}}"> <b>Email</b> </label> {{ form.email }}...

Pinax teams - given a user find all the teams for which the user is a member

django,django-models,pinax
I am using pinax-teams to model teams and memberships. Trying to see the best way to find the following: Given a user, get all the teams he is the member of. I currently have the following and it is too inefficient. Any help is appreciated. Here is the link to...

How to filter by field of field (multi level relationship) in django admin?

python,django,django-models,django-admin
With models design like this: class School(models.Model): name = models.CharField(max_length=50) class Grade(models.Model): name = models.CharField(max_length=10) school = models.ForeignKey(School) class Student(models.Model): name = models.CharField(max_length=100) grade = models.ForeignKey(Grade) Since Student object doens't have direct relation with School object, How can I filter django-admin to only display students from selected school?...

Form not showing in html - django

python,django,django-models,django-forms,modelform
I have a model that extends the User model in django, that model is a userprofile, I'll use to asociate aditional information to User model. I have the model, the form, the view, the url and the html, but the html is not showing the fiels, only shows the submit...

How to get simple ForeignKey model working? (a list of class in another class)

django,django-models,django-queryset
I tried to figure this out on my own :( couldn't quite get there. Pls take pity. . . I'm trying to represent exercise data (a start time an end time and many--an undetermined number of-- heart rates) this is the model I have set up: class HeartRate(models.Model): timestamp =...

Model friends table in Django

python,django,django-models
I am trying to write a model for Contacts table (like on mobile phone) in Django. My first idea was to create class Person which will have fields(name, phone, email, age, creation_date...), and to create class Contact that will have two fields (person1, person2). That means that person1 has person2...

Django migrations detect the same change many times

django,django-models,django-migrations
I have a model like this: MyModel(models.Model): ... date_start = models.DateTimeField( auto_now=True, editable=True ) date_end = models.DateTimeField( default=datetime.now() + relativedelta(months=3) ) ... I modified the date_end field before, and I did the migrations, it is working properly, but now it is still detecting that change as a new migration. Any...

Using .update with nested Serializer to post Image

django,rest,django-models,django-rest-framework,imagefield
I have an ImageField. When I update it with the .update command, it does not properly save. It validates, returns a successful save, and says it is good. However, the image is never saved (I don't see it in my /media like I do my other pictures), and when it...

How to filter objects for count annotation in Django?

python,django,django-models,django-aggregation
Consider simple Django models Event and Participant: class Event(models.Model): title = models.CharField(max_length=100) class Participant(models.Model): event = models.ForeignKey(Event, db_index=True) is_paid = models.BooleanField(default=False, db_index=True) It's easy to annotate events query with total number of participants: events = Event.objects.all().annotate(participants=models.Count('participant')) How to annotate with count of participants filtered by is_paid=True? I need to query...

Django OneToOneField or ForeignKey?

django,django-models,model
My models.py: class User: // fields ... class Post: // fields ... class Comment: news = models.ForeignKey(Post) user = models.???(User) Each Post can have any number of Comments. But for each Post, I want a user to have only one Comment. How do I model this? I cannot do user...

After Django update to 1.8.2 : 'OneToOneRel' object has no attribute 'unique_for_date'

django,django-models
I am getting this error after I update Django from 1.7x to 1.8.2 The affected line is Phy = models.OneToOneField(User) The same applies to many to many fields....

Django Rest Framework - Non Field Error Custom Message

python,django,django-models,django-rest-framework
I have looked at this question but that doesn't really tell me about non-field errors. My Model is: class DeviceContact(models.Model): created = models.DateTimeField(auto_now_add=True) contact_sid = models.CharField(max_length=75, db_index=True) contact_name = models.CharField(max_length=200) contact_email = models.CharField(max_length=250, db_index=True) contact_type = models.CharField(max_length=200, default='mobile') class Meta: unique_together = ("contact_sid", "contact_email", "contact_name") class...

In Django template how to separate Date and time from DateTimeField?

django,django-models,django-templates
I want to print only the date on my Django template. This is my model. class Comment(models.Model): name = models.ForeignKey(User) body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) article = models.ForeignKey(Article) Now to print both date and time on a template I can use {{object.pub_date}} to print. But I only want to...

AttributeError when establishing a foreign key using the to_field option

python,django,django-models
I am trying to establish a foreign key relationship between two models with a specific field. Establishing the relationship to the ID fields works correctly, however when I use the to_field option I get error: AttributeError: type object 'WorldEaseConsignee' has no attribute 'order_number' Sample code: class WorldEaseConsignee(models.Model): order_number = models.IntegerField(...

Django admin with inlines, 1 model with 2 foreigns keys to 2 different models

django,django-models,foreign-keys,django-admin
I have 3 models total. My main model has 2 foreign keys to 2 different models. So the relationships are setup as a many-to-one. When I try to customize the admin, I cannot get it to simply allow me to edit the main character model and have the 2 inlines...

Django Prefix the PK ID field of a Model

python,django,django-models
I don't want to use Django's own Primary Key it adds automatically to the model. Is the following possible... Prefix the PK ID field with j1_, followed by a unique ID in base 36. For example, j1_15bfi0. I have read about auto field i.e. id = models.AutoField(primary_key=True) But this does...

How to reverse query objects for multiple levels in django?

python,django,django-models
Suppose I have: Class Level1: name = CharField() Class Level2: name = CharField() level1 = ForeignKey(Level1) Class Level3: name = CharField() level2 = ForeignKey(Level2) Class Level4: name = CharField() level3 = ForeignKey(Level3) Suppose I already have an Level1 object: level1, how can get all Level4 objects of Level1? Like the...

Database first Django models

python,django,django-models,django-rest-framework,django-serializer
In ASP.NET there is entity framework or something called code first from database. Is there something similar for Django? I usually work with a pre-existing database that I need to create a backend (and subsequently a front end) for. Some of these RDBs have many tables and relations so manually...

How to deal with optional GET argument?

python,django,django-models,django-views
I have a GET request that sometimes has pk argument and sometimes hasn't. I want to have 1 view that deals with it, but my attempts to write it are not successful. Here is what I have: @ajax @login_required def search_dist(request): try: pk = request.GET.get('pk') except Exception: dist_list = request.user.distributors.all()...

Please help me decipher a traceback for “ValueError: invalid literal for int()” in my models

django,django-models,django-middleware
I am trying to create a list of ProductPart objects where ProductPart.part matches the value of an instance of Variety.variety_name. Here is a demonstration of my problem. > v = Variety.objects.get(id=2) > p = ProductPart.objects.get(id=1) > v.variety_name 'Non Pareil (Inshell)' > p.part <Variety: Non Pareil (Inshell)> > a = ProductPart.objects.values().filter(part=v.variety_name)...

Django ModelForm: Making an “Other” Textarea manditory when the user selects “Other” from RadioSelect

django,django-models,django-forms
I am converting a survey from a Form to a ModelForm in Django 1.6.2. I want to create an "Other" forms.Textarea which the user has to fill out if they select "Other" from the forms.RadioSelect. I want this to be mandatory only if the user selects "Other" from the forms.RadioSelect....

Automatic HTTPRedirect in Django view if user is authenticated?

django,django-models
I have successfully made it so the user must log in to view their profile, however, I only want the user to be able to view their profile and no one else. Previously, they could visitwww.websitename.com/user/admin as well as www.websitename.com/user/test and it would bring up the data for the profile...

Replacing ManyToMany-Relation with ModelChoiceField

python,django,django-models,django-forms
I'm stuck trying to render a ManyToMany-Relation as a ModelChoiceField instead of a ModelMultipleChoiceField. So I tried the following (simplified): models.py: class Project(models.Model): name = models.CharField(max_length=20, unique=True) manager = models.ManyToManyField(User, related_name="manager_related") forms.py: class ProjectForm(forms.ModelForm): manager = forms.ModelChoiceField(queryset=User.objects.all(), empty_label='Choose Manager', required=False) class Meta: model = Project fields = ['name', 'manager'] The...

Callable not defined for django.db.models field default

python,django,python-3.x,django-models
I am using PyCharm 4.5.2, Django 1.8.2. If I define a class as: class User(models.Model): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, default=make_slug) def make_slug(self): return self.first_name + self.last_name[0] The IDE highlights default=make_slug with make_slug being undefined. The interpretter agrees and when the development server tries to...

How to apply 'IN' constraint to the fields of django models

python,django,django-models,constraints
I want that one of the fields of the model can take only some specific values say a and b. This can be achieved normally in sql by adding the 'IN' constraint. How can I achieve the same using django model class fields. eg. Some field say fruits can have...

Django- Staying DRY with multiple model methods

django,django-models
What's the preferred way to stay DRY when using model methods that require the results of another model method? For example: class MyModel(models.Model): a = models.IntegerField() b = models.IntegerField() c = models.IntegerField() def _method_one(self): x = a + b return x method_one = property(_method_one) def _method_two(self): x = a +...

How can I avoid recursion during saving of django model

python,django,django-models
I have a model Entry Now whenever Entry is created for any date. Then before saving I need to make check and add more entries, for example e.g. Entry 1 - red Now suppose if any entry.color = red Then I also need to make two more entries like Entry...

Django date query from newest to oldest

django,django-models
I am building my first Django program from scratch and am running into troubles trying to print out items to the screen from newest to oldest. My model has an auto date time field populated in the DB as so: Model from django.db import models from django.contrib.auth.models import User from...

Django: set number of ForeignKey relations by integer value in another model

django,django-models,one-to-many
I am designing an Mturk application in Django where people rate Tweets for different outcomes (gender, personality, age, etc.). In my models I have three classes: Task (the Mturk task), Message (the Twitter message), and Outcome (the relationship I want the message annotated for). For each Task I want the...

Assign JSON field to model variable in django

django,django-models,django-rest-framework
I am having my json like: { "name": "Rahul", "2or4": 2, } Here, How can I assign my model variable : twoOrFour to jason field value "2or4" as we can not have variable start with integer. I am new to django. I am using dJango-rest-framework for this api....

Cannot create super user use custom user model in django 1.8

python,django,django-models,django-admin,django-custom-user
i try to make custom user model and i want to make super user but i am getting error like this Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File...

Django-cms/Django SingleRelatedObjectDescriptor instead of object itself

django,django-models,django-cms
I'm trying to make a plugin for django-cms and having issues passing my configuration to the CMSPluginBase class. This is my models.py; from django.db import models from mptt.models import MPTTModel, TreeForeignKey from cms.models.pluginmodel import CMSPlugin class Section(MPTTModel): name = models.CharField(max_length=25, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class MPTTMeta:...

Error on raising ValidationError as dictionary

python,django,python-2.7,django-models,django-forms
Django newbie here. I am trying to raise an error for email field in my custom form. My forms.py has following code to validate email: def clean_email(self): email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise ValidationError({'email':'Email already registered. Login to continue or use another email.'}) On entering existing...

Creating multiple model instances in DRF3

django,django-models,django-views,django-rest-framework
1) I would like to create multiple model instances with one API call, like asked here: How do I create multiple model instances with Django Rest Framework? I tried the solution named in the link, with no success. I am trying to upload multiple files in one API call. Result:...

customising a model field for serialization

django-models,django-rest-framework
I am doing a project on django. I have a model EmployeeProfile with several fields along with a field education with following data - (institute, year, course, description). in model i am storing data in form of a deliminated field. e.g. a sample value for education - " XYZ colllege...

Django Generic Foreign Key invalid literal for int() with base 10

python,django,django-models
I have a model that uses a Generic foreign key class Flag(TimeStampedModel): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') However when I try to save a new Flag where the ForeignKey is base64 encoded I get the error: ValueError: invalid literal for int() with base 10: '7_p1seHP7FR0KxN9+hHaCaNg'...

Migrate new model fields

django,postgresql,django-models,database-migration
When I use manage.py makemigrations <app> only columns with relations are migrated to pg database. How to instruct django to migrate new basic non-relational columns, like: title = models.CharField(max_length=20, null=True) I'm using django 1.8.2. on Ubuntu...

django-tables2: use request user in render method

django,django-models,django-tables2
I'm using djnago-tables2 to display data from my event model. I need to get the current request user into the render method of the table (to further call a model function to get the response of the current user). How can i do this? My Model class Event(models.Model): name=models.CharField(max_length=254) start=models.DateTimeField()...

Dynamically creating the related_name from META class

python,django,django-models
Most of my Django models use the same User Mixin, because of this I would like to dynamically create the related_name for the field. I would like it to be the class name where TestModel becomes test_models or maybe even a set name from the meta class on the main...

How to count users in JOINed models?

python,django,join,django-models,django-queryset
Let's say, we have two models: class User(models.Model): nickname = models.CharField(max_length=50) email = models.CharField(max_length=50) class Profile(models.Model): user = models.OneToOneField(User, primary_key=True) carma = models.BooleanField(default=False) birthdate = models.DateField(input_formats=['%Y-%m-%d']) How to get amount of users where: 1) all users with ages below 18? 2) all users between 18 - 25 3) all users...

Import one model inside urls.py from other app

python,django,django-models
I am trying to import model from another app inside urls.py from different app. This is my code main/settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'clients', 'rest_framework', ) main/urls.py from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.models import User, Group from rest_framework import serializers...

Setting unique=True on a ForeignKey has the same effect as using a OneToOneField

python,django,python-3.x,django-models,django-1.8
I switched to Django 1.8.2 from 1.7 recently, but I encounter with a little bit issues, for example in one of my models I have: class Author(models.Model): author = models.ForeignKey(UserProfile, blank=False, primary_key=True) timestamp = models.DateTimeField(auto_now_add=True) But when I run server I come across with this following warning: WARNINGS: exam.Author.author: (fields.W342)...