I've been following the Django documentation "Write your app tutorial" and I keep running into the above error. It seems to be coming from this line
selected_choice = question.choice_set.get(pk=request.POST['choice'])
This is my Questions and Choices object:
class Questions(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date Published')
def __str__(self):
return self.question_text
class Choices(models.Model):
questions = models.ForeignKey(Questions, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
The code is exactly as it is on the official documentation, so I can't tell exactly where the error is coming from
"choice_set" is created as an object in Questions because the Choice model has a foreignKey relationship to Questions, so for every entry in Questions, there might be some Choice instances (rows of data in the Choice table). The general rule is a lowercase version of the model name, followed by "_set".
Your model is called Choices plural (with an 's'), so the set will probably be called "choices_set". I'm pretty sure that's the remaining problem for you.
You need to define the Choice model with a foreign key to Questions, otherwise django won't create choice_set.
Your Class name is Choices, so if you try choices_set things might work
This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed last month.
I'm reading and trying to understand django documentation so I have a logical question.
There is my models.py file:
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=255)
tagline = models.TextField()
def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField()
def __str__(self):
return self.name
class Post(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
def __str__(self):
return self.headline
What is doing here each __str__ function in each class?
What is the reason I need those functions in it?
You created a Blog model. Once you migrate this, Django will create a table with "name" and "tagline" columns in your database.
If you want to interact with the database with the model, for example create an instance of the model and save it or retrieve the model from db,
def __str__(self):
return self.name
will come handy. Open the python interactive shell in your project's root folder via:
python manage.py shell
Then
from projectName.models import Blog
Blog.objects.all() # will get you all the objects in "Blog" table
Also, when you look at the models in your admin panel, you will see your objects listed, with the name property.
The problem is, the return will look like this if you did not add that function:
<QuerySet [<Blog:>,<Blog:>,<Blog:>....]
So you will not know what those objects are. A better way to recognize those objects is retrieving them by one of its properties which you set it as name. This way you will get the result as follow:
<QuerySet [<Blog:itsName>,<Blog:itsName>,<Blog:itsName>....]
If you want to test this out, run python manage.py shell and run:
from projectName.models import Blog
# The below will create and save an instance.
# It is a single step. Copy-paste multiple times.
Blog.objects.create(name="first",tagline="anything")
Blog.objects.all() # check out the result
The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this
Note: how objects are just plainly numbered
to this
.
Note: proper object names here
You could choose what to show in the admin panel, as per your choice. Be it a field value or a default value or something else.
This overrides the default name of the objects of this class, it's something like Author:object which isn't very helpful.
overriding it gives a more human friendly name of the object like the Author.name
def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised. Will see step by step.Suppose below is our code.
class topics():
def __init__(self,topics):
print "inside init"
self.topics=topics
my_top = topics("News")
print(my_top)
Output:
inside init
<__main__.topics instance at 0x0000000006483AC8>
So while printing we got reference to the object. Now consider below code.
class topics():
def __init__(self,topics):
print "inside init"
self.topics=topics
def __str__(self):
print "Inside __str__"
return "My topics is " + self.topics
my_top = topics("News")
print(my_top)
Output:
inside init
Inside __str__
My topics is News
So, here instead of object we are printing the object. As we can see we can customize the output as well. Now, whats the importance of it in a django models.py file?
When we use it in models.py file, go to admin interface, it creates object as "News", otherwise entry will be shown as main.topics instance at 0x0000000006483AC8 which won't look that much user friendly.
The __str__ function is used add a string representation of a model's object, so that is
to tell Python what to do when we convert a model instance into a string.
And if you dont mention it then it will take it by default the USERNAME_FIELD for that purpose.
So in above example it will convert Blog and Author model's object to their associated name field and the objects of Post model to their associated headline field
Django has __str__ implementations everywhere to print a default string representation of its objects. Django's default __str__ methods are usually not very helpful. They would return something like Author object (1). But that's ok because you don't actually need to declare that method everywhere but only in the classes you need a good string representation. So, if you need a good string representation of Author but not Blog, you can extend the method in Author only:
class Author(models.Model):
name = models.CharField(max_length=100)
...
def __str__(self):
return f'{self.name}' # This always returns string even if self.name is None
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
text = models.CharField(max_length=100)
author = Author.objects.create(name='David')
print(author) # David
post = Post.objects.create(author=author, text='some text')
print(post) # Post object(1)
Now, beyond Django, __str__ methods are very useful in general in Python.
More info here.
When you want to return the objects in that class then you'll see something such as <QuerySet [object(1)]>. However no body wants to see something like this. they want actual name that human can understand what exactly is present in that table, so they use this function.
For example, you define __str__() in Person model as shown below:
# "models.py"
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __str__(self): # Here
return self.first_name + " " + self.last_name
Then, you define Person admin as shown below:
# "admin.py"
from django.contrib import admin
from .models import Person
#admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
pass
Now, the full name is displayed in the message and list in "Change List" page:
And in "Change" page:
And in "Delete" page:
Next, if you don't define __str__() in Person model as shown below:
# "models.py"
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
# def __str__(self): # Here
# return self.first_name + " " + self.last_name
Now, the object name and id are displayed in the message and list in "Change List" page:
And in "Change" page:
And in "Delete" page:
Probably a very novice Django question, but here goes. In my Django project, I have this in my models
#models.py
class Classes(models.Model):
classcode = models.CharField(max_length=15)
classname = models.TextField()
students = models.ManyToManyField(User)
class Test(models.Model):
classes = models.ForeignKey(Classes, on_delete=models.CASCADE)
name = models.TextField(max_length=100)
points = models.ManyToManyField(User, default=0)
I also have a form for Test, which is:
#forms.py
class TestForm(forms.ModelForm):
class Meta:
model = Test
fields = ('classes', 'name')
When I get to the actual form, the drop-down menu for 'classes' in TestForm merely comes up with 'Classes object' for the number of 'Classes' that I have in my DB. I want to change that so the form lists the names of the classes, which are stored in the 'Classes' model as 'classname'
Can anyone point me in the right direction please?
The easiest way to do it is to provide a string representation of your object, this would replace any where you access the class throughout your application
class Classes(models.Model):
classcode = models.CharField(max_length=15)
classname = models.TextField()
students = models.ManyToManyField(User)
def __str__(self):
return "{0}: {1}".format(self.classcode, self.classname)
From the docs
The __str__ (__unicode__ on Python 2) method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance.
I need to set up default Foreign Key for a model at the model declaration stage (in models.py). I use the following code:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return str(self.pub_date)
def create_question():
q=Question(question_text='default text', pub_date=datetime.now())
q.save()
return q.id
class Choice(models.Model):
question = models.ForeignKey(Question, default=lambda: create_question())
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
This works fine, the Choice instance and associated Question instance are created... But saving of Choice instance leads to creation of two additional (useless) Question instances. It seems like that default-lambda is called several times during Choice instance saving. I don't need these additional Question instances. How to avoid their creation?
NOTE: In python-shell everything works well:
c=Choice(votes=5, choice_text='dim')
c.save()
creates one instance of Choice and one associated instance of Question. Only using admin save button leads to extra Question instances creation!
I would like to show one attribute from another class. The current class has a foreign key to class where I want to get the attribute.
# models.py
class Course(models.Model):
name = models.CharField(max_length=100)
degree = models.CharField(max_length=15)
university = models.ForeignKey(University)
def __unicode__(self):
return self.name
class Module(models.Model):
code = models.CharField(max_length=10)
course = models.ForeignKey(Course)
def __unicode__(self):
return self.code
def getdegree(self):
return Course.objects.filter(degree=self)
# admin.py.
class ModuleAdmin(admin.ModelAdmin):
list_display = ('code','course','getdegree')
search_fields = ['name','code']
admin.site.register(Module,ModuleAdmin)
So what i'm trying to do is to get the "degree" that a module has using the "getdegree". I read several topics here and also tried the django documentation but i'm not an experienced user so even I guess it's something simple, I can't figure it out. Thanks!
It is pretty straight forward.
Try this:
def getdegree(self):
return self.course.degree
Documentation here
You can do this safely because course is not a nullable field. If it were, you should have checked for existence of object before accessing its attribute.