html - 模态 POST 中的 HTML 表单正在工作,但没有写入数据库 Django
问题描述
我是 Django 框架的新手。我开发了一个带有表格和添加按钮的页面。单击“添加”按钮时,它将在模式中打开表单。这里的问题是当我第一次尝试时,表格中的数据按预期填充到表格中。但是之后,当我做同样的事情时,它给了 200 用于 POST,而表中没有填写任何内容。并且没有显示错误。
这是我的示例代码。
<!--modal for Create record-->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<form method="POST" class="modal-dialog modal-md" action=".">{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"><strong>Add Company</strong></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="form-group row">
<label for="companyName" class="col-12 col-md-4"><strong>Company Name</strong></label>
<div class="col-12 col-md-10">
<input type="text" class="form-control" id="companyName" name="companyName" placeholder="Company Name">
</div>
</div>
<div class="form-group row">
<label for="address" class="col-12 col-md-4"><strong>Address</strong></label>
<div class="col-12 col-md-10">
<input type="text" class="form-control" id="address" name="address" placeholder="Address">
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary">Reset</button>
<button type="submit" class="btn btn-primary">Add</button>
<button type="close" class="btn btn-light" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
这是views.py中的代码
def addcompany(request):
if request.method == 'POST':
if request.POST.get('companyName') and request.POST.get('address'):
saverecord = company()
saverecord.CompanyName = request.POST.get('company')
saverecord.Address = request.POST.get('address')
saverecord.save()
return render(request, 'newapp/companypage.html')
else:
return render(request, 'newapp/companypage.html')
如果有人能帮助我解决这个问题,我将不胜感激。谢谢你。
解决方案
我认为公司名称中的错误应该这样写:
saverecord.CompanyName = request.POST.get('companyName')
您还可以阅读有关如何使用 Django 从模型构建表单的更多信息
推荐阅读
- scala - 减少使用 shapeless HList 时的编译时间
- twitter-bootstrap - 一个块接一个块引导程序?
- c# - 如何在 selenium 中为这个 HTML 元素创建相对路径?
- python - 图例中的颜色与图表颜色不匹配
- spring-boot - 如何自定义序列化
- javascript - 三.js TransformControls
- php - 如何执行 shell_exec 命令
- android - 自定义滚动视图类中的 Expandablelistview
- python - 从今天的日期获取熊猫数据框中最近的未来日期
- mysql - 影响单行内的多个(或所有)列的单个条件检查