6๐
โ
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">×</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
๐คscafrs
Source:stackexchange.com