You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django如何实现仅作者可查看自身私密帖子?求修正方案

改进方案

问题分析

你的views.py存在多处逻辑错误:

  • filter方法用法错误,无法直接传入自定义函数进行过滤
  • 内部函数recipe_private语法错误(调用recipe(is_private=True)是错误的属性访问方式),且未正确返回值,同时错误使用self.request.user(视图函数中直接用request.user即可)
  • 未区分登录/未登录用户的访问权限逻辑,且Python循环过滤的效率远低于数据库层面的ORM查询

修正后的代码

1. 优化views.py

首先导入Django的Q查询对象来组合复杂条件,然后按用户登录状态过滤帖子:

from django.db.models import Q
from django.shortcuts import render
import recipes.models as models  # 确保导入正确的模型

def home(request):
    if request.user.is_authenticated:
        # 登录用户:显示所有公开帖子 + 自己的私密帖子
        recipes = models.Recipe.objects.filter(
            Q(is_private=False) | Q(is_private=True, author=request.user)
        ).order_by('-created_at')  # 可选:按创建时间倒序排列
    else:
        # 未登录用户:仅显示公开帖子
        recipes = models.Recipe.objects.filter(is_private=False).order_by('-created_at')
    
    context = {'recipes': recipes}
    return render(request, "recipes/home.html", context)

2. 补充详情页权限控制(可选)

为了防止用户直接通过URL访问他人的私密帖子,需要在详情视图中添加权限校验:

from django.shortcuts import get_object_or_404, HttpResponseForbidden

def recipe_detail(request, pk):
    recipe = get_object_or_404(models.Recipe, pk=pk)
    
    # 权限判断:私密帖子仅作者可访问
    if recipe.is_private and recipe.author != request.user:
        return HttpResponseForbidden("你无权查看该私密帖子")
    
    context = {'recipe': recipe}
    return render(request, "recipes/recipe_detail.html", context)

如果使用基于类的视图,可以更简洁地实现:

from django.contrib.auth.mixins import UserPassesTestMixin
from django.views.generic import DetailView

class RecipeDetailView(UserPassesTestMixin, DetailView):
    model = models.Recipe
    template_name = "recipes/recipe_detail.html"

    def test_func(self):
        recipe = self.get_object()
        # 公开帖子所有人可见,私密帖子仅作者可见
        return not recipe.is_private or recipe.author == self.request.user

3. models.py无需修改

你的Recipe模型定义是正确的,is_private字段默认设为True表示新帖子默认私密,符合需求。

内容的提问来源于stack exchange,提问作者C0untV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 03:27:23