Django Tutorial part 2 Field Error - django

I got a field error when I was trying to run the tutorial of Django Part 2. I'm using Python 3.6 and Django 1.11.
models.py
import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
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_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Working with the tutorial, step by step. I was running the python manage.py shell:
>>> from polls.models import Question, Choice
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
I got the following error after Question.objects.filter(question_text__startswith='What'):
django.core.exceptions.FieldError: Cannot resolve keyword 'question_text_startswith' into field. Choices are: choice, id, pub_date, question_text
I don't know what to do to repair this error, maybe I put something wrong at models, that's why I share models.py with you. I hope you can help me

You should have 2 underscores before startswith.
Try
Question.objects.filter(question_text__startswith='What')

Related

Django filter F and functions of fields. Filter by comparison between fields with lookups

models
from django.db import models
from django.utils import timezone
import datetime
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.FloatField(default=0)
# ...
def __str__(self):
return self.choice_text
creation
#from polls.models import Choice, Question;from django.utils import timezone
#q = Question(question_text="What's new?", pub_date=timezone.now());q.add(Choice(choice_text='variant', votes=0),Choice(choice_text='Not much', votes=0),Choice(choice_text='Just hacking again', votes=0),Choice(choice_text='The sky', votes=0));q.save;q = Question(question_text="m?", pub_date=timezone.now());q.save
#q = Question(question_text="Third question", pub_date=timezone.now());q.add(Choice(choice_text='single option', votes=0));q.save()
what I am trying to do is filter questions by question_text length being more than amount of choices(children):
#from django.db.models import Count,F, Func,Value
#q=Question.objects.all()
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{3}')#works
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(3)+'}')#works
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(F('no'))+'}')
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(F('nod'))+'}')
#q.filter(question_text__regex=r'.{'+str(F('choice__count'))+'}')
#q.filter(question_text__regex=r'.{'+str(Count('choice'))+'}')
#Question.objects.filter(question_text__regex = r'.{'+(str(Count('choice')))+'}')
#q.filter(question_text__regex=r'.{'+str(Count([1]))+'}')
#q.filter(question_text__regex=r'.{'+str(Count([1,2,2,2,2,2,2,2,2,2,2,2,2,2]))+'}')
#q.annotate(no=Func(F('question_text'), function='LENGTH')).filter(question_text__regex=r'.{'+str(F("no"))+'}')
#q.annotate(no=Func(F('question_text'), function='LENGTH')).filter(no__gte=F('choice__count'))#works
#q.filter(question_text__regex=r'.{'+str(F("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Count("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Count("choice"))+'}')
#q.filter(question_text__regex=r'.{'+str(Value("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Value("choice__count"))+'}')
question, which has length longer than amount of choices

Django Polls tutorial - Admin list filter error

I'm working on the polls tutorial for Django and I can't seem to get the list filter to work. The instruction on the tutorial is simply to add the following line to QuestionAdmin:
list_filter = ['pub_date']
When I do python manage.py runserver on Terminal, I get this:
ERRORS:
: (admin.E108) The value of 'list_display[0]' refers to 'question_text', which is not a callable, an attribute of 'QuestionAdmin', or an attribute or method on 'polls.Question'.
: (admin.E108) The value of 'list_display[1]' refers to 'pub_date', which is not a callable, an attribute of 'QuestionAdmin', or an attribute or method on 'polls.Question'.
: (admin.E116) The value of 'list_filter[0]' refers to 'pub_date', which does not refer to a Field.
My code for the polls/admin.py:
from django.contrib import admin
from .models import Choice, Question
# Register your models here.
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
list_display = ('question_text','pub_date','was_published_recently')
list_filter = ['pub_date']
admin.site.register(Question, QuestionAdmin)
My code for polls/models.py:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Where is ...
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
... part from Writing your first Django app, part 1?
BTW this line
# ...
means that some code which was previously explained omitted but you obviously need it ... so return to first tutorial page and recheck everything ...

Django tutorial choice_set

From the Django tutorial:
I've defined my models as follows:
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self): # Python 3: def __str__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self): # Python 3: def __str__(self):
return self.choice_text
Where is choice_set defined and how does this work?
>>> p = Poll.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
I don't know how deep an explanation you want, but Django defines it for you when you do poll = models.ForeignKey(Poll).
You can read here about it.
choice_set wasn't defined anywhere.
Django creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Poll object p has access to a list of all related Choice objects via the choice_set attribute: p.choice_set.all().
So choice_set. Where choice is your Choice model in lowercase and _set is kind of Django Manager Tool.
In details, you can read right here .

Django tutorial unicode not working

I have the following in my models.py
import datetime
from django.utils import timezone
from django.db import models
# Create your models here.
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_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
but when I enter
from polls.models import Poll, Choice
Poll.objects.all()
I don't get
Poll: What's up?
but
Poll: Poll object
Any ideas?
Django 1.5 has experimental support for Python 3, but the Django 1.5 tutorial is written for Python 2.X:
This tutorial is written for Django 1.5 and Python 2.x. If the Django version doesn’t match, you can refer to the tutorial for your version of Django or update Django to the newest version. If you are using Python 3.x, be aware that your code may need to differ from what is in the tutorial and you should continue using the tutorial only if you know what you are doing with Python 3.x.
In Python 3, you should define a __str__ method instead of a __unicode__ method. There is a decorator python_2_unicode_compatible which helps you to write code which works in Python 2 and 3.
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
#python_2_unicode_compatible
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question
For more information see the str and unicode methods section in the Porting to Python 3 docs.

Trouble with _unicode() method in django

I'm adding a unicode() method to my model, however when displaying all objects in the interactive it's not working.
import datetime
from django.db import models
from django.utils import timezone
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_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def _unicode_(self):
return self.choice
# Create your models here.
(InteractiveConsole
>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: Poll object>]
They need to be named __unicode__ (two underscores on either side). This is an awkward detail of Python reserved methods that is not immediately obvious by looking at them.
The django docs show you how to specify a unicode method in your model:
https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#other-model-instance-methods
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
Note: These are DOUBLE underscores, where in your example you are only using single underscores.
Its a standard python special class method, as listed here