如何对查询集进行编码,以便用户只能在配置文件部分中看到自己的帖子

问题描述 投票:0回答:1

我正在使用Django 2.06开发一个项目。我有多个用户,他们可以发帖,其他人可以阅读他们的帖子,这是非常正常的。在用户个人资料页面,用户应该看到自己的帖子。这是我被困的地方,我如何编码查询集,然后在配置文件部分用户只能看到自己的帖子。

代码演示

class ProfileView(ListView):

    template_name = "profile.html"
    queryset = QuickWord.objects.filter()
    context_object_name = 'quickword'


    def get_context_data(self, **Kwargs):
        context = super(ProfileView, self).get_context_data(**Kwargs)
        context['addproduct'] = AddProduct.objects.filter()
        context['article_view'] = Article.objects.filter()
        context['edit'] = Profile.objects.all().last()
        return context

我知道我必须使用过滤器值,但不知道如何做到这一点。

谢谢

python django python-3.x django-2.0
1个回答
0
投票

假设你的author模型中有一个Post字段,你应该在你的views.py做这样的事情

def profile(request):
    user_posts = Post.objects.filter(author=request.user)

    return render(request, 'path/to/profile.html', {'posts': user_posts})

当然,上面的视图要求用户登录。

© www.soinside.com 2019 - 2024. All rights reserved.