Model Django Poll - python

I am working through the Django tutorials, and now I am at creating a poll.
The code below works fine until I want to create choices, where for some reason I always get this error message:
line 22, in __unicode__
return self.question
AttributeError: 'Choice' object has no attribute 'question'
What am I doing wrong?
Here's my code:
import datetime
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.question # this is line 22

The __unicode__ method on the Choice model should look something like:
def __unicode__(self):
return self.poll.question
question attribute does not exist on the Choice model, you need to reach for it over the poll foreign key field.
Don't forget to check out Django's great documentation that shows many examples on how to handle many to one relationships.
Edit
It would probably make more sense to return self.choice in Choice model __unicode__ method so it outputs the actual choice not the Poll question.
def __unicode__(self):
return self.choice

To follow up on rebus's answer, the tutorial actually says to add different returns to each model:
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
You had 'self.question' as the return for both - I'm thinking you made the same copy/paste error I did, or the tutorial previously had that error ;-)

It should be:
def __unicode__(self):
return self.poll.question
Because poll is a related model that contains the question.

This is due to a Human Brain error or a copy/paste error. We/You thought that both functions were same and copy-pasted the same code for both, but there was one word different in both.
replace question to choice in line 22

Related

'Questions' object has no attribute 'choice_set'

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

when I use object name I get 'DeferredAttribute' object has no attribute 'get'

I'm new with django. I'm really confused with views filters.
Here is my models.py:
class Author(models.Model):
title = models.CharField(max_length=30)
user=models.ForeignKey(User)
age= models.CharField(max_length=2)
post= models.ManyToManyField(Article)
def __str__(self):
return self.title
def __str__(self):
return self.post
def __str__(self):
return self.age
class Meta:
ordering = ('title','user',)
Here is my views.py:
def posting(request):
details = Author.age.get(pk=request.user.id)
return render(request,'home.html' , {'detail':details})
Now I need to get the current logged in user (age or title or post). When I execute the code I get the above error. How can I filter the particular object of logged in user?
Kindly suggest me some docs for views filter.
You access fields after returning a model instance via the manager (default manager is named objects), not directly:
author = Author.objects.get(user=request.user)
age = author.age
Talking about some docs, the Django documentation is a good starting point.

Django get attributes from foreign key's class

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.

Adding a computed default value to Django model, how?

I'm trying to learn Python and Django by implementing an online forum. Right now, I'm trying to set the default value of the post title to "Re:" + thread.title, but I can't seem to do it.
I've searched for anything like this but nothing seems to answer my problem.
Here's my code (models.py):
from django.db import models
class Thread(models.Model):
title = models.CharField(max_length=50)
def __unicode__(self):
return u'[id=%s]%s' % (self.id, self.title)
class Post(models.Model):
thread = models.ForeignKey(Thread)
title = models.CharField(max_length=50)
post_date = models.DateTimeField(auto_now_add=True)
content = models.TextField()
def __init__(self):
super(Post, self).__init__()
if not self.title:
self.title = "Re: %s" % self.thread.title
def __unicode__(self):
return u'%s::[id=%s]%s' % (self.thread, self.id, self.title)
I hope someone can help me.
Regards,
Chad
You probably want to set the default value in the overridden save method. Your __init__ code doesn't work because at that point self.thread is not set yet.

Error following django tutorial

I'm trying to follow the django tutorial but I get this error and I can't continue.
http://dpaste.com/630957/
Can someone help me?
(I'm new with python and django) Thank you so much.
From the error log:
File "/arpa/h/huksy007/Projects/mysite/polls/models.py" in __unicode__
22. return self.question
Make sure that self actually has a property called question.
You forgot to put that line on your Choice Model:
choice = models.CharField(max_length=200)
It need to be like that:
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
EDIT:
Sorry, I was thinking of something else and didn't realize it was this line you should change to your model:
def __unicode__(self):
return self.choice
You probably have this on your Choice model:
def __unicode__(self):
return self.question
And question its from the Poll model.

Categories