Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My Django form is not rendering when I use Bootstrap's modal

I have some trouble with rendering a Django form in a modal. I suspect it is because I need some Ajax to get the url in the browser but I don't know how.

Form:

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

View:

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})

Urls:

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>

Some pics

The non working modal form: Imgur

Forms works when accessed directly through link: Imgur

Can somebody help me out? I render the form fields manually but I just cut it with form.as_p otherwise the question would not validate because there was too much code.

like image 717
Raf Rasenberg Avatar asked Nov 20 '25 10:11

Raf Rasenberg


1 Answers

I think that if you can open the modal and you do not visualize the formulary, it is because you are not loading it, try to do this:

Add this in your views.py

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

Add this in your urls.py

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

in your html

Place this on the page from which you plan to open your modal and wrap your button in a 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>

Create a different html for the modal and add an id to your form

<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>

in your 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) {

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

This answer will take you to the next question how to respond after sending the data from the modal. Therefore, you must do the following in the view you are handling the request.

First import the following in views.py

from django.http import JsonResponse

And in the view that handles the request copy this

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
like image 185
fralejanro Avatar answered Nov 23 '25 03:11

fralejanro