Error following django tutorial - python

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.

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

Django Tutorial - choice_set typeerror

So I was looking at this post to try and resolve some issues encountered in my Django tutorial:
TypeError: 'choice_text' is an invalid keyword argument for this function in django tutorial
this is my code:
from polls.models import Question, Choice
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice='Not much', votes=0)
I'm still facing exactly the same problem after taking the suggested solution of changing "choice_text" to "choice" - i.e exactly the same error message, and the documentation version for the Django tutorial is for Django 1.11 (my version). Does anybody know the correct syntax for creating choice sets?
Thanks!
Supplementary Information: My models.py file defining Question and Choice.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_texct = models.CharField(max_length=200)
votes = models.IntegerField(default = 0)
def __str__(self):
return self.choice_text
You have a typo in model:
choice_texct = models.CharField(max_length=200)
# ^^^^
need replace
choice_text = models.CharField(max_length=200)
# ^^^^
and don't forget do migrations,
Or in your code need
q.choice_set.create(choice_text='Not much', votes=0)
replace to
q.choice_set.create(choice_texct='Not much', votes=0)
# ^^^^^

Get record from master table if alteast one record exists in slave/child tables using django api

To elaborate
e.g.
I have two models "Subject" and "Question"
class Subject(models.Model):
title = models.CharField(max_length=200,unique=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.title
class Question(models.Model):
title = models.CharField(max_length=500)
is_active = models.BooleanField(default=True)
subject = models.ForeignKey('Subject')
def __str__(self):
return self.title
I want the list of active subjects having at least one active question.
I have done initial search and also checked django queryset api, but did not got answer.
I am not looking for raw sql query option.
I hope this clears the query. I have tried django api, but did not get expected result. I think this is very obvious query and there should be simple answer to it.
Thanks in advance for any help.
Did you try this?
Subject.objects.filter(question__id__isnull=False).distinct()
You might even be able to simplify it to the following, but I'm too lazy to look up if it's correct or try it out:
Subject.objects.filter(question__isnull=False).distinct()

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.

Model Django Poll

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

Categories