当我使用 Bootstrap 的模态时,我的 Django 表单没有呈现

Raf*_*erg 3 python django django-forms bootstrap-modal

我在模态中渲染 Django 表单时遇到一些问题。我怀疑这是因为我需要一些 Ajax 来获取浏览器中的 url,但我不知道如何。

形式:

class TrackedWebsitesForm(forms.ModelForm):
    class Meta:
        model = TrackedWebsites
        fields = "__all__"
Run Code Online (Sandbox Code Playgroud)

看法:

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})
Run Code Online (Sandbox Code Playgroud)

网址:

urlpatterns = [
    path('web', views.web),
Run Code Online (Sandbox Code Playgroud)

创建网站.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>
Run Code Online (Sandbox Code Playgroud)

一些照片

非工作模态形式: 伊姆古尔

直接通过链接访问时,表单可以工作: 伊姆古尔

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

fra*_*nro 6

我认为,如果您可以打开模式并且看不到处方集,那是因为您没有加载它,请尝试执行以下操作:

将其添加到您的views.py中

def add_employee(request):
    form = TrackedWebsitesForm()
    return render(request, 'your_template', {'form':form})
Run Code Online (Sandbox Code Playgroud)

将其添加到您的 urls.py 中

path('employee/add', views.add_employee, name='add_employee'),
Run Code Online (Sandbox Code Playgroud)

在你的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>
Run Code Online (Sandbox Code Playgroud)

为模式创建不同的 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>
Run Code Online (Sandbox Code Playgroud)

在你的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) {

                  },});      
              });
          });
      });
  });
Run Code Online (Sandbox Code Playgroud)

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

首先在views.py中导入以下内容

from django.http import JsonResponse
Run Code Online (Sandbox Code Playgroud)

并在处理请求的视图中复制此内容

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
Run Code Online (Sandbox Code Playgroud)