I have a page with 3 forms, the forms are essentially the same in terms of fields but have different validation, I was wondering if instead of having multiple forms is there any way of having one form with dynamic validation, and then passing a keyword to the form to use one validation or another.
Here is my forms.py:
class FileTypeOneForm(forms.Form):
statement = forms.FileField(label='')
def clean_statement(self):
statement_file = self.cleaned_data['statement_file']
# Check statement_file format and raise ValidationError in case of invalid format
# ...
return statement_file
class FileTypeTwoForm(forms.Form):
statement = forms.FileField(label='')
def clean_statement(self):
statement_file = self.cleaned_data['statement_file']
# Check statement_file format and raise ValidationError in case of invalid format ** required format is different than FileTypeOneForm and FileTypeThreeForm required format **
# ...
return statement_file
class FileTypeThreeForm(forms.Form):
Options = [
('', 'Select'),
('one', 'One'),
('two', 'Two')
]
option = forms.ChoiceField(label='', choices=Options)
statement = forms.FileField(label='')
def clean_statement(self):
statement_file = self.cleaned_data['statement_file']
# Check statement_file format and raise ValidationError in case of invalid format ** required format is different than FileTypeOneForm and FileTypeTwoForm required format **
# ...
return statement_file
All three forms have the same field statement_file, but with different validation, and the third form has a second field option.
Currently there is views.py:
form_id = request.POST.get('form_id')
if form_id == 'one':
form_one = FileTypeOneForm(request.POST, request.FILES)
# ... Process form data ...
# Restart all the other forms
form_two, form_three = FileTypeTwoForm(), FileTypeThreeForm()
elif form_id == 'two':
form_two = FileTypeTwoForm(request.POST, request.FILES)
# ... Process form data ...
# Restart all the other forms
form_one, form_three = FileTypeOneForm(), FileTypeThreeForm()
elif form_id == 'three':
form_three = FileTypeThreeForm(request.POST, request.FILES)
# ... Process form data ...
# Restart all the other forms
form_one, form_two = FileTypeOneForm(), FileTypeTwoForm()
I'd want to make this cleaner by having a single form with dynamic validation, and maybe an optional field option for the third form, any suggestions on how to do this?