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

Django问题:无法将错误信息传递至模板上下文

问题分析与修复

核心问题

触发错误条件后,你立刻执行了return redirect('show', pk=note.id),这会直接跳转到笔记详情页,导致后续渲染错误提示的代码完全没机会运行,所以模板永远接收不到error变量。

修复步骤

  1. 调整跳转逻辑:只有当邀请操作成功时才跳转,错误情况下留在当前页面并展示提示
  2. 补全render的模板参数:原代码中render函数缺少模板文件名,这会导致Django找不到模板文件

修复后的视图函数:

def invite_user(request, pk):
    note = get_object_or_404(Note, pk=pk)
    form = InviteUser()
    err = False

    if request.method == 'POST':
        form = InviteUser(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            # 拆分条件,提升可读性
            user_exists = User.objects.filter(username=username).exists()
            not_self = username != request.user.username
            not_already_member = not Note.objects.filter(members__contains=[username], id=note.id).exists()
            
            if user_exists and not_self and not_already_member:
                target_user = User.objects.get(username=username)
                notification = Notification(
                    message=f"Do you want to join {note.user.username}'s note: {note.title}?",
                    user=target_user,
                    note_id=note.id
                )
                notification.save()
                # 仅成功邀请时跳转
                return redirect('show', pk=note.id)
            else:
                print('Error')
                err = True

    # 组装上下文并渲染页面
    context = {'form': form}
    if err:
        context['error'] = 'You cannot invite this user!'
    
    # 替换为你的实际模板文件名,比如'invite_user.html'
    return render(request, 'invite_user.html', context)

额外优化点

  • 拆分复杂判断条件为单独变量,提升代码可读性
  • 提前获取目标用户对象,避免重复查询数据库
  • 修正原代码中User.objects.get(username=note.user)的错误,note.user本身是User对象,直接调用note.user.username即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:22:21