I want to do "contextal" form validation in django. Consider this case:
PLACE_TYPES = (
('RESTAURANT', 'Restaurant'),
('BARCLUB', 'Bar / Club'),
('SHOPPING', 'Shopping'),
)
RESTURANT_FORMAT_CHOICES = (
('FAST_FOOD', 'Fast Food'),
('FAST_CASUAL', 'Fast Casual'),
('CASUAL', 'Casual'),
('CHEF_DRIVEN', 'Chef Driven'),
)
class Place(models.Model):
place_type = models.CharField(max_length=48, choices=PLACE_TYPES, blank=False, null=False)
name = models.CharField(max_length=256)
website_1 = models.URLField(max_length=512, blank=True)
hours = models.CharField(max_length=1024, blank=True)
geometry = models.PointField(srid=4326, blank=True, null=True)
#Restaurant Specific
restaurant_format = models.CharField(max_length=128, choices=RESTAURANT_FORMAT_CHOICES, blank=True, null=True)
So in the django admin, the corresponding form for Place will have pulldown menu with choices like "resturant, bar, club", and there is another field called "restaurant_format".
Validation should make sure restaurant_field cannot be null if the first pulldown was set as "restaurant".
I am trying something like this:
class PlaceAdminForm(forms.ModelForm):
def clean(self):
if self.cleaned_data['place_type'] == 'RESTAURANT':
if self.cleaned_data['place_type'] is None:
raise forms.ValidationError('For a restaurant you must choose a restaurant format')
but get this error:
Exception Type: KeyError
Exception Value:
place_type
Exception Location: /place/admin.py in clean, line 27