【问题标题】:How can I code the query set in order that the users can see only their own post in profile section如何对查询集进行编码,以便用户只能在个人资料部分看到他们自己的帖子
【发布时间】:2018-12-21 02:14:34
【问题描述】:

我正在使用 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

我知道我必须使用过滤器值,但不知道该怎么做。

谢谢

【问题讨论】:

  • 您的Article 模型看起来如何?你如何存储用户写了什么帖子?

标签: python django python-3.x django-2.0


【解决方案1】:

假设您的 Post 模型中有一个 author 字段,您应该在您的 views.py 中执行类似的操作

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

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

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

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    相关资源
    最近更新 更多