I'm working on an advanced search page of a Django (3.2) project. I'm using pure javascript and Django's formset_factory to create a dynamic form where the user can create a hierarchy of forms containing advanced search criteria (for and/or groups). It works great. However...
Early on during development, before I wrote the javascript to pass the additional hierarchy information to views.py
's form_valid
method, Django (without me adding any specific code to do so) was performing nice form validation before submit and would present a nice tooltip that pointed to missing form fields, and the form (desirably) would not submit:
When I implemented the javascript to save the hierarchy information, attached to a listener on the submit button, I noticed that the tooltip would appear for a fraction of a second and the invalid form would inappropriately submit. Here's the code that was introduced that inadvertently bypassed Django's automatic form validation:
<script>
document.addEventListener("DOMContentLoaded", function(){
appendInnerSearchQuery(document.querySelector('.hierarchical_search'), 0, rootGroup);
var myform = document.getElementById("hierarchical_search_form");
document.getElementById("advanced_search_submit").addEventListener("click", function () {
saveSearchQueryHierarchy(document.querySelector('.hierarchical_search'));
myform.submit();
});
});
console.log("Ready with rootGroup: ", rootGroup);
</script>
In fact, subsequent efforts appear to submit even before the tooltip has a chance to show up, presumably due to the time it takes to validate, and the form is submitted before Django's automatic form validation has completed.
I understand why this breaks/overrides Django's automatic form validation. What I have been trying to figure out is:
- How do I (in javascript) wait for Django's automatic form validation to complete?
- How do I check the result of the form validation in javascript, so I can decide whether or not to call
myform.submit()
?
I have been googling this for a couple days now and cannot find anything that tells me how to, in javascript, retrieve Django's automatic form validation result. Everything I have found addresses validating in javascript from scratch. I would rather use Django's automatic validation mechanisms, so I can specify them in the class I created in forms.py
.