The first thing you can do is simplify testing for cases where you want to see if only one of the two fields is filled. You can implement a logical xor as follows:
if bool(description2) != bool(location2):
or as follows:
if bool(description2) ^ bool(location2):
I also think that it would be more clear if you implemented a clean method for each field separately, as described in. This ensures that the error appears in the right field and allows you to simply raise forms.ValidationError , and not directly access the _errors object.
For instance:
def _require_together(self, field1, field2): a = self.cleaned_data.get(field1) b = self.cleaned_data.get(field2) if bool(a) ^ bool(b): raise forms.ValidationError(u'You must specify a location and description') return a
To get behavior that requires location1 , just use required=True for this field and it will be processed automatically.
source share