From 170d55d64e899273bf79124ed25e973f5337c89e Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Tue, 27 Oct 2020 22:52:01 +1100 Subject: [PATCH] Add custom form validation step --- InvenTree/InvenTree/views.py | 26 ++++++++++++++++++++++-- InvenTree/part/templates/part/build.html | 2 +- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/InvenTree/InvenTree/views.py b/InvenTree/InvenTree/views.py index f73be6bd4e..87c517f9e2 100644 --- a/InvenTree/InvenTree/views.py +++ b/InvenTree/InvenTree/views.py @@ -10,6 +10,7 @@ from __future__ import unicode_literals from django.utils.translation import gettext_lazy as _ from django.template.loader import render_to_string +from django.core.exceptions import ValidationError from django.http import JsonResponse, HttpResponseRedirect from django.urls import reverse_lazy @@ -320,6 +321,15 @@ class AjaxCreateView(AjaxMixin, CreateView): - Handles form validation via AJAX POST requests """ + def validate(self, cleaned_data, **kwargs): + """ + Hook for performing any extra validation, over and above the regular form.is_valid + + If any errors exist, raise a ValidationError + + """ + return True + def pre_save(self, form, request, **kwargs): """ Hook for doing something before the form is validated @@ -356,12 +366,24 @@ class AjaxCreateView(AjaxMixin, CreateView): self.request = request self.form = self.get_form() + # Perform regular form validation + valid = self.form.is_valid() + + # Perform any extra validation steps + if valid: + try: + valid = valid and self.validate(self.form.cleaned_data) + except ValidationError as e: + valid = False + + self.form.add_error(None, e) + # Extra JSON data sent alongside form data = { - 'form_valid': self.form.is_valid(), + 'form_valid': valid } - if self.form.is_valid(): + if valid: self.pre_save(self.form, request) self.object = self.form.save() diff --git a/InvenTree/part/templates/part/build.html b/InvenTree/part/templates/part/build.html index d7ca33c673..e54bc51f47 100644 --- a/InvenTree/part/templates/part/build.html +++ b/InvenTree/part/templates/part/build.html @@ -11,7 +11,7 @@
{% if part.active %} {% if roles.build.add %} - + {% endif %} {% endif %}