对象必须是django中类型的实例或子类型

时间:2017-02-01 09:13:23

标签: django django-models django-views django-class-based-views

我从djangobook学习django并且在django文档中有一个基于类的视图的例子,here,我的问题是我得到了一个我尝试运行此错误时出错。

应该跟踪上次有人看过的时间 作者:

models.py

class Author(models.Model):
    salutation = models.CharField(max_length=10, null=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField(blank=True, verbose_name='e-mail')
    headshot = models.ImageField(upload_to='author_headshots', null=True, blank=True)
    last_accessed = models.DateTimeField(null=True)

urls.py

urlpatterns = [
    url(r'^authors/(?P<pk>[0-9]+)/$', views.AuthorDetailView.as_view(), name='AuthorDetailView'),
]

views.py

class AuthorDetailView(DetailView):

    def get_object(self, queryset=Author.objects.all()):
        # Call the superclass
        object_1 = super(Author, self).get_object()

        # Record the last accesed date
        object_1.last_accessed = timezone.now()
        object_1.save()

        # Return the object
        return object_1

错误:

Traceback (most recent call last):
  File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/alex/Documents/Proiecte/Django/Django_tutorial/venv/lib/python3.5/site-packages/django/views/generic/detail.py", line 115, in get
    self.object = self.get_object()
  File "/home/alex/Documents/Proiecte/Django/Django_tutorial/mysite/books/views.py", line 179, in get_object
    object_1 = super(Author, self).get_object()
TypeError: super(type, obj): obj must be an instance or subtype of type

1 个答案:

答案 0 :(得分:4)

您的get_object方法正在尝试调用super,但您需要传入当前的类名而不是模型名称

    object_1 = super(Author, self).get_object()

应该是

    object_1 = super(AuthorDetailView, self).get_object()
    object_1 = super().get_object()  # The args can be omitted for Python 3