首页 > 解决方案 > 模态 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')

如果有人能帮助我解决这个问题,我将不胜感激。谢谢你。

标签: htmldjango-viewsdjango-templatesbootstrap-modal

解决方案


我认为公司名称中的错误应该这样写:

            saverecord.CompanyName = request.POST.get('companyName')

您还可以阅读有关如何使用 Django 从模型构建表单的更多信息


推荐阅读