Django 如何按URL指定用户名查询对应用户发布的帖子
修改方案
核心调整点
- 不再用当前登录用户的Profile做帖子过滤条件,改为从URL路径参数中提取目标username,匹配对应Profile后做过滤
- 补充无效用户的404兜底逻辑
- 原有搜索、点赞标记逻辑无需改动
前置依赖导入
先在views.py顶部补充需要的导入(如果已经导入可跳过):
from django.shortcuts import get_object_or_404 from django.db.models import Q # 替换为你项目中实际的Profile模型导入路径 from accounts.models import Profile from .models import MyPost, PostLike
修改后的完整视图代码
class UserPostList(LoginRequiredMixin, SelectRelatedMixin, generic.ListView): login_url = "accounts:signin" raise_exception = False model = models.MyPost select_related = ('uploaded_by',) context_object_name = 'myposts' template_name = 'posts/user_post_list.html' def get_queryset(self): # 提取URL中定义的username参数 target_username = self.kwargs.get('username') # 查询目标用户的Profile,查询失败直接返回404 target_profile = get_object_or_404(Profile, user__username=target_username) # 原有搜索逻辑保留 si = self.request.GET.get("si") if si is None: si = "" # 替换过滤条件为目标用户的Profile postList = MyPost.objects.filter( uploaded_by=target_profile ).filter( Q(subject__icontains=si) | Q(message__icontains=si) ).order_by("-id") # 点赞状态仍按当前登录用户判断,逻辑保留 for p1 in postList: p1.liked = False ob = PostLike.objects.filter(post=p1, Liked_by=self.request.user.profile.user) if ob: p1.liked = True return postList
逻辑说明
self.kwargs是Django类视图自动存储的URL路径参数字典,对应urls.py中定义的<str:username>字段get_object_or_404会在输入的username不存在时直接返回404页面,避免无效参数返回空列表的问题- 若你的Profile模型与User的关联外键字段名不是
user,将get_object_or_404里的查询条件user__username替换为对应字段即可 - 点赞逻辑无需修改:无论查看的是哪个用户的帖子列表,点赞状态都应该对应当前登录用户对这条帖子的操作状态,和被查看用户无关
内容的提问来源于stack exchange,提问作者saurabhjdsingh
相关产品推荐
相关产品推荐

