I am reading django official tutorial ( http://docs.djangoproject.com/en/dev/intro/tutorial01/ ). When i try run "python manage.py shell", python throw error:
File "D:\DjangoProjects\mysite\polls\models.py", line 8
def __unicode__(self):
^
IndentationError: unexpected indent
Help please! How solve this problem?
models.py:
import datetime
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
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
You have a python indentation error. I'm not exactly sure where, but the django docs show this: http://docs.djangoproject.com/en/dev/intro/tutorial01/
So follow it to the letter /space.
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
Your exact indentation you've pasted wouldn't throw that error, but in your real code, you must have the def __unicode__ line at the exact indent depth as the other lines in your model.
Make sure you are using spaces and not tabs for all of your indents, as tabs can sometimes make the indent level seem the same as the others.
Related
I am learning web develpoment by django. I am coding according to the book django2byexample.
I found a problem that the book hasn't include
My VScCode printInstance of 'DateTimeField' has no 'year' member
Could someone tell me what` the problem?Thank you.
Here is the code:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published'))
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now())
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager()
published = PublishedManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',args=[self.publish.year,self.publish.month,self.publish.day,self.slug])
i find the answer.
It is the problem of vscode.
we can set in this following step:
Then in Visual Studio Code goto: User Settings (Ctrl + , or File > Preferences > Settings if available ) Put in the following (please note the curly braces which are required for custom user settings in VSC):
{"python.linting.pylintArgs": [
"--load-plugins=pylint_django"
],}
Reference:Class has no objects member
This is a VSC problem. However, you can suppress the warning for a certain code block
def get_absolute_url(self):
#pylint: disable=E1101
return reverse('blog:post_detail',
args=[
self.publish.year,
self.publish.month,
self.publish.day,
self.slug])
Here you only disable the E1101 error for the get_absolute_url method as in the second line of the code. If you want to re-enable it, you can write #pylint: enable=E1101 at the end of the block which it has been disabled for.
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')
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 .
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.
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