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

Django中get_queryset报错User not found,如何显示用户信息?

问题分析与解决方案

首先,咱们先拆解你遇到的两个核心问题:

1. 为什么会报「User not found」错误?

你在get_queryset里写的first_name = get_object_or_404(User,first_name=self.kwargs.get('first_name'))完全是多余且错误的——你的URL配置里只传递了username参数,self.kwargs.get('first_name')拿到的是None,用None去查User的first_name字段自然会找不到用户,抛出404错误。而且你已经通过username拿到了目标用户,根本不需要再查一遍first_name。

2. 为什么页面拿不到first_name?

view.kwargs里只有URL中定义的参数(也就是username),你没在URL里传first_name,自然从这里拿不到。要显示用户的名字,得从数据库的User或UserProfileInfo模型里取,而不是从URL参数里找。

另外,不能定义两个get_queryset方法——类里方法名重复会直接覆盖,而且get_queryset的作用是返回视图要渲染的数据集(这里是Post列表),不是用来获取额外用户信息的。


修复方案

第一步:修正视图类

重写get_context_data方法,把用户的个人信息(UserProfileInfo)添加到模板上下文中,这样模板就能直接调用了:

class UserPostListView(ListView):
    model = Post
    template_name = 'mainapp/user_posts.html'
    context_object_name = 'posts'

    def get_queryset(self):
        # 只通过username获取目标用户,移除错误的first_name查询
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-published_date')

    def get_context_data(self, **kwargs):
        # 先获取父类生成的上下文
        context = super().get_context_data(**kwargs)
        # 拿到当前用户
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        # 获取用户的Profile(用get_or_create避免用户没有Profile的情况)
        user_profile, created = UserProfileInfo.objects.get_or_create(user=user)
        # 将Profile添加到上下文,供模板使用
        context['user_profile'] = user_profile
        return context

第二步:修改模板代码

把模板里的{{ view.kwargs.first_name }}改成从上下文的user_profile对象中获取:

<div class="sidebar">
    <p class="active" href="#">{{ view.kwargs.username }}</p>
    <button class="commentbtn"><a class="aclass" href="#">Connect with {{ view.kwargs.username }}</a></button>
    <!-- 从上下文的user_profile中读取first_name -->
    <p>{{ user_profile.first_name }}</p>
    <p>Lorem</p>
</div>

第三步:URL配置保持不变

你的urls.py不需要修改,原配置没问题:

path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),

额外说明

如果你的业务逻辑中,User模型本身的first_name字段(Django默认User模型自带)和UserProfileInfo的first_name是同步的,也可以直接在模板里用{{ user_profile.user.first_name }},但根据你给出的UserProfileInfo定义,直接用{{ user_profile.first_name }}更符合你的扩展字段设计。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:45:30