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

ModelForm将提交按钮值存入数据库问题求助

表单异常问题解决:数据库存储提交按钮值而非用户输入

问题原因

你的HTML表单中,提交按钮的name属性设为了"post",这和ModelForm绑定的Post模型里的post字段名称完全一致。表单提交时,request.POST字典会同时包含输入框的post值和按钮的post值,由于字典键名重复,按钮的value(比如默认的"Post")会覆盖输入框的内容,最终导致数据库存储的是按钮值而非用户输入。

解决方案

1. 修改HTML提交按钮的name属性

直接移除提交按钮的name属性(提交按钮无需传递数据,仅需触发提交动作),或者改为其他不冲突的名称,比如submit_post。

修改后的HTML代码:

<form action="{% url 'index' %}" method="post">
    {% csrf_token %}
    <div>
        {{ newpostform }}
    </div>
    <input id='post-btn' class="btn btn-primary" type="submit" value="Post">
</form>

2. 优化views.py逻辑(可选)

处理用户未登录的边界情况,同时用重定向避免刷新页面重复提交表单:

from django.shortcuts import render, redirect

def index(request):
    newpostform = NewPostForm()
    username = request.user.get_username() if request.user.is_authenticated else None

    if request.method == 'POST':
        if not username:
            return redirect('login')  # 未登录用户重定向到登录页
        post_instance = Post(author=username)
        newpostform = NewPostForm(request.POST, instance=post_instance)
        if newpostform.is_valid():
            newpostform.save()
            return redirect('index')  # 提交成功后重定向,避免重复提交

    return render(request, "network/index.html", {
        "newpostform": newpostform
    })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 10:05:16