I'm trying to write a clean method form one of my forms in Django 1.5.
The user has the ability to chose from a list of pre existing objects or inserting one by himself, but he have to do one of this two things (if he do both the ModelChoiceField has precedence in the relative view).
This is the incriminated form's part:
class UploadFileForm(forms.Form):
subject = forms.ModelChoiceField(queryset=Subject.objects.all(), required=False, label='What subject this file is about?')
subject1 = forms.CharField(required=False, label="Or insert your subject if you didn't find it in the menu")
def clean_subject(self):
subject = self.cleaned_data.get('subject')
subject1 = self.cleaned_data.get('subject1')
if not subject and not subject1:
raise forms.ValidationError('This field is required.')
whitch is relative to this model:
class Subject(models.Model):
subject = models.CharField(max_length = 30, primary_key=True, blank=False, null=False)
problem is: if the user let the ModelChoiceField empty and tries to insert a value in the CharField the form raises the error anyway (and of course it shouldn't).
I also tryed: subject1 = self.cleaned_data.get('subject1', None) but in this case the subject1 value will always be None (so the problem it's basically the same).
I'm really going crazy trying to undestrand why.
You should use clean method instead of clean_<fieldname> to validate fields that depend on each other (Django clean() docs).
class UploadFileForm(form.Form):
subject = forms.ModelChoiceField(queryset=Subject.objects.all(), required=False)
subject1 = forms.CharField(required=False)
def clean(self):
subject = self.cleaned_data.get('subject')
subject1 = self.cleaned_data.get('subject1')
if not subject and not subject1:
raise forms.ValidationError('Subject field is required.')
return self.cleaned_data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With