【问题标题】:Trouble using "Slug" in Django DetailView在 Django DetailView 中使用“Slug”时遇到问题
【发布时间】:2013-08-17 12:11:49
【问题描述】:

models.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)


urls.py

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


views.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().


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

谢谢!!!

【问题讨论】:

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


    【解决方案1】:

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

    它会,但你还没有告诉它要使用什么型号。这个错误很清楚:

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

    您可以使用modelqueryset 属性来执行此操作,或者使用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():
            ....
    

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

    【讨论】:

    • 谢谢!!实际上这解决了错误,但现在由于某种原因它给了我一个“页面未找到:找不到与查询匹配的标签”错误:(((...。为什么 Django 无法根据 slug 字段找到 Tag 对象..?
    猜你喜欢
    • 2017-07-02
    • 2013-03-30
    • 1970-01-01
    • 2022-01-15
    • 2013-06-23
    • 2012-04-25
    • 1970-01-01
    • 2013-08-17
    • 2020-03-07
    相关资源
    最近更新 更多