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

Django实现表单新输出换行展示且不覆盖历史内容

嘿,这个问题我熟!你现在遇到的核心问题是Django的HTTP请求是无状态的,每次提交新问题都会重置页面内容,所以得把对话历史存起来才行。咱们分两步搞定:

第一步:修改Django视图,用Session存储对话历史

Django的Session可以帮我们在用户会话期间保留数据,不用额外数据库就能临时存对话记录。修改你的视图函数:

from django.shortcuts import render
# 导入你的NLTK问答处理函数,比如你之前写的get_bot_response
def get_bot_response(user_input):
    # 这里是你的NLTK逻辑,比如基于规则或训练好的模型生成回复
    if "hello" in user_input.lower():
        return "Hi there! How can I help you?"
    elif "bye" in user_input.lower():
        return "Goodbye! Have a great day!"
    else:
        return "Sorry, I don't understand that question yet."

def chatbot_index(request):
    # 从Session获取历史对话,不存在就初始化空列表
    chat_history = request.session.get('chat_history', [])
    
    if request.method == 'POST':
        user_question = request.POST.get('user_question', '')
        if user_question.strip():
            # 调用你的NLTK逻辑生成回复
            bot_reply = get_bot_response(user_question)
            # 把当前问答添加到历史记录
            chat_history.append({
                'user': user_question,
                'bot': bot_reply
            })
            # 别忘了更新Session里的历史记录!
            request.session['chat_history'] = chat_history
    
    # 把历史记录传给模板
    return render(request, 'index.html', {'chat_history': chat_history})

第二步:修改index.html模板,展示所有历史对话

原来的模板只显示最新回复,现在要循环遍历历史记录,把每一条对话都渲染出来:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>NLTK Chatbot on Django</title>
    <!-- 加个简单样式让对话更易读 -->
    <style>
        .chat-box {
            max-width: 600px;
            margin: 20px auto;
        }
        .message {
            padding: 10px;
            margin: 8px 0;
            border-radius: 8px;
        }
        .user-message {
            background-color: #dcf8c6;
            text-align: right;
        }
        .bot-message {
            background-color: #f0f0f0;
        }
        form {
            max-width: 600px;
            margin: 0 auto;
            display: flex;
            gap: 10px;
        }
        input[type="text"] {
            flex: 1;
            padding: 8px;
            font-size: 16px;
        }
        button {
            padding: 8px 16px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="chat-box">
        <h2>Chat with NLTK Bot</h2>
        <!-- 遍历历史对话,渲染每一条 -->
        {% for chat in chat_history %}
            <div class="message user-message">
                <strong>You:</strong> {{ chat.user }}
            </div>
            <div class="message bot-message">
                <strong>Bot:</strong> {{ chat.bot }}
            </div>
        {% endfor %}
    </div>

    <!-- 提问表单 -->
    <form method="POST">
        {% csrf_token %}
        <input type="text" name="user_question" placeholder="Type your question here..." required>
        <button type="submit">Send</button>
    </form>
</body>
</html>

额外注意点

  1. URL配置:确保你的urls.py里有对应的路由,比如:
from django.urls import path
from . import views

urlpatterns = [
    path('', views.chatbot_index, name='chatbot_home'),
]
  1. Session持久化:默认Django Session在浏览器关闭后会失效,如果需要长期保存对话,可以考虑用数据库存储(比如创建一个ChatHistory模型,关联用户),或者设置SESSION_COOKIE_AGE延长有效期。
  2. 进阶优化:如果不想每次提交都刷新页面,可以用AJAX异步提交请求,动态更新对话内容,体验会更流畅,但上面的方案是最基础可靠的同步实现,先解决覆盖问题再优化也没问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:49:58