Django taggit相关文章未显示在模板上

时间:2019-08-27 02:34:35

标签: django django-taggit

最近我安装了django-taggit并包含在帖子模型中。我做了视图和URL文件,没有错误。在主页上,我得到一些帖子和与帖子相关的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 %}

1 个答案:

答案 0 :(得分:0)

context_object_name中的TagIndexView与您要在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'))