2

模型.py

class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)     
    slug = models.SlugField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Tag, self).save(*args, **kwargs)


网址.py

url(r'^tag/(?P<slug>[A-Za-z0-9_\-]+)/$', TagDetailView.as_view(), name='tag_detail'),      


视图.py

class TagDetailView(DetailView):
    template_name = 'tag_detail_page.html'
    context_object_name = 'tag'


好吧,我认为这不会有任何问题,因为 Django 的通用 DetailView 会寻找“slug”或“pk”来获取它的对象。但是,导航到“localhost/tag/RandomTag”会给我一个错误:

错误:

ImproperlyConfigured at /tag/RandomTag/

TagDetailView is missing a queryset. Define TagDetailView.model, TagDetailView.queryset, or override TagDetailView.get_queryset().


有谁知道为什么会这样……???

谢谢!!!

4

1 回答 1

4

因为 Django 的通用 DetailView 会寻找“slug”或“pk”来获取它的对象

它会,但你还没有告诉它要使用什么模型。错误非常清楚:

定义 TagDetailView.model、TagDetailView.queryset,或覆盖 TagDetailView.get_queryset()。

您可以使用modelorqueryset属性来执行此操作,或者使用get_queryset()方法:

class TagDetailView(...):
    # The model that this view will display data for.Specifying model = Foo 
    # is effectively the same as specifying queryset = Foo.objects.all().
    model = Tag

    # A QuerySet that represents the objects. If provided, 
    # the value of queryset supersedes the value provided for model.
    queryset = Tag.objects.all()

    # Returns the queryset that will be used to retrieve the object that this 
    # view will display. By default, get_queryset() returns the value of the
    # queryset attribute if it is set, otherwise it constructs a QuerySet by 
    # calling the all() method on the model attribute’s default manager.
    def get_queryset():
        ....

有几种不同的方法可以告诉视图您希望它从哪里获取对象,因此请阅读文档以获取更多信息

于 2013-08-15T10:06:50.140 回答