HTML 模态内的表单 POST 正在工作但未写入数据库 Django

HTML form inside modal POST is working but not writing to database Django

我是 Django 框架的新手。我开发了一个带有 table 和添加按钮的页面。单击“添加”按钮时,它将在模式内打开表单。这里的问题是当我第一次尝试时,表单中的数据按预期填充到 table 。但是之后,当我做同样的事情时,它为 POST 给出了 200,而 table 中没有任何内容。并且没有错误显示。

这是我的示例代码。

<!--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')

您还可以阅读有关如何构建的更多信息forms from models with Django