My model form class looks like:
class ParamForm(forms.ModelForm):
model = Param
fields = '__all__'
def clean(self):
comparison = self.cleaned_data.get('comparison')
score = self.cleaned_data.get('score')
if comparison and score % 2 == 0:
raise ValidationError('Since this is a range param, score cannot be even')
return self.cleaned_data
Want to test clean() method of ParamForm class and unable to make the ParamForm object as it keeps raising error ValueError: ModelForm has no model class specified.
Any ideas on how to make ParamForm object or test clean() without instantiating ParamForm?
Please have a look at the django docs for ModelForm. There, you can see that the model = ...
and fields = ...
lines should be set as attributes of the Meta class, nested inside of the ModelForm child class (ParamForm in your case).
If you want to override the clean method, you need to make sure to call the parent class’ clean method somewhere in the method definition (ie super().clean()
). But a better approach in your case is probably to add clean_<fieldname>()
methods instead of overriding the “main” clean method. This is mentioned in the django docs I linked above, but I think this section on form validation from the MDN django tutorial might be a bit easier to follow.