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

Django中Public_Profile视图获取用户Question报404错误的解决方法

问题解决:用户个人资料页加载用户提问时出现404错误

错误原因

视图中错误地用Profile的slug去匹配Question的slug,但Question的slug是基于自身标题生成的,和Profile的slug完全无关,导致get_object_or_404找不到对应Question触发404。同时需求是展示该用户的所有提问,而非单个提问,用get_object_or_404(返回单个对象)不符合需求。

分步解决方案

1. 修正视图逻辑

修改public_profile视图的Question查询逻辑,同时简化点赞数统计:

@login_required(login_url='login')
def public_profile(request, slug):
    profile = get_object_or_404(Profile, slug=slug)
    # 改为查询该用户发布的所有Question,而非用Profile的slug匹配Question的slug
    questions = Question.objects.filter(user=profile.user)
    # count()方法不会抛出异常,直接统计即可
    number_of_likes = Like.objects.filter(post__user=profile.user).count()
    
    context = {
        'profile': profile,
        'number_of_likes': number_of_likes,
        'questions': questions
    }
    return render(request, 'public_profile.html', context)

2. 修正模板遍历逻辑

视图传递的是questions(多个Question对象的查询集),模板需要用循环遍历展示每个提问:

<div class="container">
    <div class="row justify-content-center">
       <div class="col">
        <ul class="list-group">
          {% for question in questions %}
            <li class="list-group-item">{{ question.title }}</li>
          {% empty %}
            <li class="list-group-item">该用户暂无提问</li>
          {% endfor %}
        </ul>
      </div>
    </div>
   </div>

3. (可选)修复Question模型的slug唯一性问题

当前Question的slug仅基于标题生成,若有相同标题的提问,保存时会因slug唯一约束报错。可以修改save方法,加入ID或序号保证slug唯一:

from django.utils.text import slugify
import itertools

def save(self, *args, **kwargs):
    if not self.slug:
        base_slug = slugify(self.title)
        self.slug = base_slug
        # 检查slug是否已存在,若存在则自动添加序号
        for num in itertools.count(1):
            if not Question.objects.filter(slug=self.slug).exists():
                break
            self.slug = f"{base_slug}-{num}"
    super().save(*args, **kwargs)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:24:23