首页 > 解决方案 > 如何在通用视图中传递 slug (Django)

问题描述

我如何在这个通用的“ListView”中传递一个 slug,我被 get_context_data 函数弄糊涂了。蛞蝓在“轮廓”模型中。

视图.py

class PostListView(ListView):
    model = Post
    template_name = 'feed/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated:
            liked = [i for i in Post.objects.all() if Like.objects.filter(user = self.request.user, post=i)]
            context['liked_post'] = liked
        return context

标签: djangodjango-modelsdjango-views

解决方案


正如 Indox 建议的那样,我不需要向视图添加任何额外的代码,我在 url 模式上使用了 slug:slug ,并且在我的模板中有一个 {% url 'home' user.profile.slug %} ,最后我错过了 user.profile.slug,在添加它工作正常之后。


推荐阅读