属性错误:'NoneType'对象没有属性'id'

bla*_*ght 0 python django django-models web

我已经达到了Mozilla Django教程的第4章,但后来我遇到了这个错误.我按照它说的所有内容进行了操作,但是当我尝试从管理面板打开BookInstance模型时,它给了我这个错误:

/ admin/catalog/bookinstance /'NoneType'对象中的AttributeError没有属性'id'

这是我的代码,models.py(我突出显示了发生错误的部分):

from django.db import models
from django.core.urlresolvers import reverse

class Book(models.Model):
    """
    Model representing a book (but not a specific copy of a book).
    """
    title = models.CharField(max_length=200)
    author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
      # Foreign Key used because book can only have one author, but authors can have multiple books
      # Author as a string rather than object because it hasn't been declared yet in file.
    summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
    isbn = models.CharField('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
    genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
      # ManyToManyField used because Subject can contain many books. Books can cover many subjects.
      # Subject declared as an object because it has already been defined.

    def display_genre(self):
        """
        Creates a string for the Genre. This is required to display genre in Admin.
        """
        return ', '.join([ genre.name for genre in self.genre.all()[:3] ])
        display_genre.short_description = 'Genre'


    def get_absolute_url(self):
        """
        Returns the url to access a particular book instance.
        """
        return reverse('book-detail', args=[str(self.id)])

    def __str__(self):
        """
        String for representing the Model object.
        """
        return self.title



import uuid # Required for unique book instances

class BookInstance(models.Model):
    """
    Model representing a specific copy of a book (i.e. that can be borrowed from the library).
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library")
    book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
    imprint = models.CharField(max_length=200)
    due_back = models.DateField(null=True, blank=True)

    LOAN_STATUS = (
        ('d', 'Maintenance'),
        ('o', 'On loan'),
        ('a', 'Available'),
        ('r', 'Reserved'),
    )

    status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='d', help_text='Book availability')

    class Meta:
        ordering = ["due_back"]


    def __str__(self):
        """
        String for representing the Model object
        """
        ***return '%s (%s)' %(self.id,self.book.title)***
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激!

编辑:这是完整的错误 单击此处查看错误

编辑:修复它

我换了它

        return str('%s (%s)'% (self.id, self.book.title))
Run Code Online (Sandbox Code Playgroud)

Sur*_*ano 6

book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)在这里你已添加null=True并在你要添加的__str__方法中self.book.title,假设如果self.book是None,那么它将无法获得self.book.title.

你也在误导'('这里的右括号 return '%s (%s)' %(self.id,self.book.title)

添加if条件以检查是否self.book不是None.

    def __str__(self):
        """
        String for representing the Model object
        """
        if self.book:
            return '%s (%s)' %(self.id, self.book.title))
        else:
            return '%s (%s)' %(self.id, self.imprint)) # add some other value that you want here
Run Code Online (Sandbox Code Playgroud)