【问题标题】:Django taggit related post not showing on templateDjango taggit 相关帖子未显示在模板上
【发布时间】:2019-12-31 04:24:26
【问题描述】:

最近我安装了 django-taggit 并包含在 post 模型中。我做了视图和网址文件,没有错误。在主页上,我得到了一些帖子和与帖子相关的 10 个标签。当我单击其中一个标签时,它会转到正确的标签,但页面是空白的。我在这里想念什么?任何帮助,将不胜感激。

这是我的代码,views.py、urls.py、home.html

def home(request):
    tutorial_list = Post.objects.all().order_by('-id')[:3]

    context = {
        'tutorial_list': tutorial_list,
    }
    return render(request, "home.html", context)


class TagMixin(object):
    def get_context_data(self, **kwargs):
        context = super(TagMixin, self).get_context_data(**kwargs)
        context['tags'] = Tag.objects.all()
        return context

class TagIndexView(TagMixin, ListView):
    template_name = 'home.html'
    model = Post
    context_object_name = 'post'

    def get_queryset(self):
        return Post.objects.filter(tags__slug=self.kwargs.get('slug'))

'''urls.py'''
path('tag/<slug:slug>/', views.TagIndexView.as_view(), name='tagged'),

'''home.html'''
{% for tutorial in tutorial_list %}
{{ tutorial.title }}
{% endfor %}
{% for tag in tags %}
<li><a href="{% url 'tagged' tag.slug %}">{{ tag.name }}</a></li>
{% endfor %}

【问题讨论】:

    标签: django django-taggit


    【解决方案1】:

    TagIndexView 的 context_object_name 与您在 home.html 中迭代的变量名称不匹配 - 模板使用的是 tutorial_list,因此 context_object_name 应该是 'tutorial_list' 而不是 'post'。

    class TagIndexView(TagMixin, ListView):
        template_name = 'home.html'
        model = Post
        context_object_name = 'tutorial_list'
    
        def get_queryset(self):
            return Post.objects.filter(tags__slug=self.kwargs.get('slug'))
    

    【讨论】:

    • 你说得对,现在完美运行。我不确定 context_object_name 的作用。谢谢你。@azundo
    猜你喜欢
    • 2011-10-25
    • 2012-12-18
    • 1970-01-01
    • 2017-09-28
    • 2019-02-06
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多