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

Django用HttpResponseRedirect实现表单无刷新提交出现AttributeError如何解决

报错原因

Django render 函数的第一个参数要求必须是当前请求的 request 对象,你错误将 HttpResponseRedirect 类作为第一个参数传入。模板渲染过程中上下文处理器需要读取 request.META 属性获取客户端信息,而HttpResponseRedirect 类不存在该属性,因此触发 AttributeError。

同时你对HttpResponseRedirect的使用也存在逻辑错误:HttpResponseRedirect用于返回重定向响应,本身会触发浏览器页面跳转,完全无法实现无刷新提交的需求,属于对原解决方案的误解。

修复步骤

第一步:修复现有代码语法错误

修改views.py中displayDict函数,修正render参数,同时修复变量未定义的隐患:

def displayDict(request):
    m = ChatStream.objects.none()
    html_ss = ''
    last_user = ''
    ip = visitor_ip_address(request)
    try:
        m = ChatStream.objects.filter()
        last = m.latest()
        last_ss =  last.ss
        last_user =  last.user
        html_ss = markdown.markdown(last_ss)
    except ChatStream.DoesNotExist:
        pass # 异常时直接使用预先定义的默认值
    
    return render(request, 'chatStream.html',
    {"chat": m, "html_ss": mark_safe(html_ss), "last_user": mark_safe(last_user)})

第二步:实现无刷新提交功能

无刷新提交需要通过AJAX实现表单异步提交,不走原生表单的整页刷新逻辑:

  1. 修改前端模板代码:
<!-- 给聊天内容加容器,方便后续JS动态更新 -->
<div id="chat-container">
{% for chat_stream in chat %}
    <p>
    {% if not forloop.last %}
        <b>ss:</b> <br> {{chat_stream.ss}} <br>
        <b>{{user}}:</b> <br> {{chat_stream.user}} <br>
    {% endif %}
    </p>
{% endfor %}
</div>

<!-- 给表单加id,方便JS绑定事件 -->
<form id="chat-form" action="/send/" method="post">{% csrf_token %}
    <input type="text" name="userMessage" required>
    <input type="submit" value="Send to ss bot">
</form>  

<!-- 新增AJAX提交逻辑 -->
<script>
const chatForm = document.getElementById('chat-form')
chatForm.addEventListener('submit', function(e) {
    // 阻止原生表单提交的整页刷新行为
    e.preventDefault()
    const formData = new FormData(this)
    fetch(this.action, {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(res => {
        if (res.status === 'success') {
            // 手动更新页面聊天内容
            const newChat = document.createElement('p')
            newChat.innerHTML = `<b>ss:</b> <br>${res.ss} <br><b>${res.user}:</b> <br>${res.user_msg} <br>`
            document.getElementById('chat-container').appendChild(newChat)
            // 清空输入框
            chatForm.reset()
        }
    })
})
</script>
  1. 修改/send/路径对应的视图函数,返回JSON响应而非重定向:
from django.http import JsonResponse

def send(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'msg': '请求方法错误'}, status=405)
    user_msg = request.POST.get('userMessage', '').strip()
    if not user_msg:
        return JsonResponse({'status': 'error', 'msg': '消息不能为空'}, status=400)
    # 这里替换为你调用聊天机器人生成回复的原有逻辑
    bot_reply = "这里是机器人的回复内容"
    # 保存聊天记录到数据库
    ChatStream.objects.create(
        user=user_msg,
        ss=bot_reply
    )
    return JsonResponse({
        'status': 'success',
        'user_msg': user_msg,
        'ss': bot_reply,
        'user': request.user.username if request.user.is_authenticated else '访客'
    })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:06:03