Django - 语法错误

时间:2014-05-17 14:28:36

标签: python django django-models

我正在从djangobook学习Django,在安装了管理员应用程序的第6章中,syncdb命令在models.py中返回语法错误(return u'%s %s' % (self.first_name, self.last_name)

我正在使用Python 3。

为什么会这样?如何解决?

models.py:

from django.db import models

class Publisher (models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website=models.URLField()

    def __unicode__(self):
        return self.name

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

    def __unicode__(self):
        return self.title

错误:

  File "C:\Users\karthikeyan\Desktop\NightHawk\Hawk\books\models.py", line 20
    return u'%s %s' % (self.first_name, self.last_name)
                  ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:5)

您在Python 3中使用Python 2语法。虽然Python 3.3及更高版本支持使用u前缀来支持unicode字符串值(以支持跨版本代码),但Python <3.2>之前 < / em>的;删除u前缀以使其有效:

def __unicode__(self):
    return '%s %s' % (self.first_name, self.last_name)

但是,您还需要查阅Django Porting to Python 3文档并使用__str__,而不是__unicode__

def __str__(self):
    return '%s %s' % (self.first_name, self.last_name)

如果您关注的是某本书,则可能需要安装Python 2。