Django动态表单提交无响应,数据无法写入sqlite3数据库问题求助
问题原因及解决方案
1 表单点击提交无响应的直接原因:JS事件拦截了提交行为
你给整个<form>标签绑定了onclick = addRem事件,点击表单内任意元素都会触发该函数。当你点提交按钮时,触发逻辑走到else分支执行return false,直接阻止了表单的默认提交动作,所以点了没任何反应。
修复方案:修改JS的事件绑定逻辑,不要把点击事件绑在整个form上,只绑定给加/减按钮即可。修改后的scriptinfra.js参考:
window.onload = function(){ // 只给加减按钮绑定事件,不要绑整个form const addBtn = document.getElementById('add'); const remBtn = document.getElementById('rem'); const main = document.querySelector('.container'); addBtn.onclick = () => { const row = ` <section class="row"><div class="col-lg-4 mb-2"> <input name='Infraestructura[]' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='Tiempo[]' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='Costo[]' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section>`; main.insertAdjacentHTML('beforeEnd', row); }; remBtn.onclick = () => { let rows = main.querySelectorAll('.row'); if (rows.length > 1) { rows[rows.length-1].remove(); } }; }
注意这里顺便把输入框的name加了[]后缀,用来传递多个同名字段的值。
2 后台存数据失败的核心原因:变量名与模型类重名
你的views.py里把表单字段值赋值给了变量Infraestructura,刚好和你的模型类同名,后续调用Infraestructura.objects.create时,实际调用的是字符串而不是模型类,直接触发报错。
修复方案:修改变量名,不要和模型类重名,同时配合动态表单的数组name,用getlist拿所有值批量存储,修改后的views.py参考:
from .models import Infraestructura # 确保你已经导入了模型类 def infraestructura(request): if request.method =='POST': # 用getlist拿所有同名字段的值 infra_list = request.POST.getlist('Infraestructura[]') tiempo_list = request.POST.getlist('Tiempo[]') costo_list = request.POST.getlist('Costo[]') # 循环批量创建数据 for infra, tiempo, costo in zip(infra_list, tiempo_list, costo_list): # 空行跳过不存 if infra.strip(): # 数字字段做类型转换,避免格式错误 try: tiempo_val = int(tiempo) if tiempo.strip() else None costo_val = int(costo) if costo.strip() else None Infraestructura.objects.create( Infraestructura=infra, Tiempo=tiempo_val, Costo=costo_val ) except ValueError: # 数字格式不对的情况可以按需加处理逻辑 pass return render (request, "Portafolio/Infraestructura.html")
其他排查点
- 确保你已经执行了
python manage.py makemigrations和python manage.py migrate,模型已经同步到数据库 - 开发阶段开启DEBUG模式,提交时如果有报错可以直接看到具体原因
- 确认urls.py中已经正确配置了
infraestructura路径的POST访问权限
内容的提问来源于stack exchange,提问作者Thrillidas
相关产品推荐
相关产品推荐

