使用Bootstrap的模式时,我的Django表单未呈现

时间:2019-03-25 12:28:27

标签: python django django-forms bootstrap-modal

以模态渲染Django表单时遇到一些麻烦。我怀疑是因为我需要一些Ajax才能在浏览器中获取url,但我不知道如何。

表格:

class TrackedWebsitesForm(forms.ModelForm):
    class Meta:
        model = TrackedWebsites
        fields = "__all__"

查看:

def web(request):
    if request.method == 'POST':
        form = TrackedWebsitesForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/websites')
            except:
                pass
    else:
        form = TrackedWebsitesForm()
    return render(request,'dashboard/create_website.html',{'form':form})

网址:

urlpatterns = [
    path('web', views.web),

create_website.html:

<div id="addEmployeeModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">

<form method="POST" class="post-form" action="/web">
  {% csrf_token %}
  <div class="modal-header">
    <h4 class="modal-title">Add website</h4>
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  </div>
  <div class="modal-body">
    <div class="form-group">
     {{ form.as_p }}
  </div>
  <div class="modal-footer">
    <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
    <input type="submit" class="btn btn-success" value="Add">
  </div>
</form>

</div>
</div>
</div>

一些图片

非工作模式形式: Imgur

通过链接直接访问时,表单有效: Imgur

有人可以帮我吗?我手动呈现表单字段,但我只是用form.as_p剪切了它,否则该问题将无法验证,因为代码太多。

1 个答案:

答案 0 :(得分:4)

我认为,如果您可以打开模态并且不可视化配方,那是因为您没有在加载它,请尝试执行以下操作:

将此添加到您的views.py

def add_employee(request):
    form = TrackedWebsitesForm()
    return render(request, 'your_template', {'form':form})

将此添加到您的urls.py

path('employee/add', views.add_employee, name='add_employee'),

在您的html

将其放置在您打算从中打开模式并将其包装在div中的页面上

 <div id="addEmployee">
    <a style="float:right" class="btn btn-success" >
        <i class="fas fa-fw fa-plus"></i> 
        <span>Add New Employee</span>
    </a>
</div>

<div id="addEmployeeModal" class="modal fade" role="dialog">
</div>

为模态创建一个不同的html,并在表单中添加一个ID

<div class="modal-dialog">
    <div class="modal-content">
        <form id="addEmployeeForm" method="POST" class="post-form" action="/web">
            {% csrf_token %}
                <div class="modal-header">
                    <h4 class="modal-title">Add website</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>
                <div class="modal-body">
                <div class="form-group">
                    {{ form.as_p }}
               </div>
               <div class="modal-footer">
                   <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
                   <input type="submit" class="btn btn-success" value="Add">
               </div>
        </form>
    </div>
</div>

在您的js中

$(document).ready(function () {

    let my_modal = $("#addEmployeeModal");
    const url_form = "/employee/add";

    $("#addEmployee a").click(function () {
      my_modal.load(url_form, function () {
          my_modal.modal("show"); // Open Modal
          $("#addEmployeeForm").submit(function (e) {
              e.preventDefault(); // Cancel the default action
              $.ajax({
                  method: "POST",
                  data: $(this).serialize(),
                  dataType: "json",
                  url: "/url that handles the request/",
                  success: function (response) {
                      my_modal.modal('hide');
                  },
                  error: function (response) {

                  },});      
              });
          });
      });
  });

此答案将带您进入下一个问题,即从模态发送数据后如何响应。因此,必须在正在处理请求的视图中执行以下操作。

首先将以下内容导入views.py

from django.http import JsonResponse

然后在处理请求的视图中复制此

if form.is_valid ():
    ...
    response = JsonResponse ({"message": 'success'})
    response.status_code = 201 // indicates that the request has been processed correctly
    return response
else:
    ...
    response = JsonResponse ({"errors": form.errors.as_json ()})
    response.status_code = 403 // indicates that there was an error processing the request
    return response