Django中的上下文表单验证

Django中的上下文表单验证,django,django-admin,validation,Django,Django Admin,Validation,我想在django中进行“上下文”表单验证。考虑这种情况: PLACE_TYPES = ( ('RESTAURANT', 'Restaurant'), ('BARCLUB', 'Bar / Club'), ('SHOPPING', 'Shopping'), ) RESTAURANT_FORMAT_CHOICES = ( ('FAST_FOOD', 'Fast Food'), ('FAST_CASUAL', 'Fast Casual'), ('CA

我想在django中进行“上下文”表单验证。考虑这种情况:

PLACE_TYPES = (
    ('RESTAURANT', 'Restaurant'),
    ('BARCLUB', 'Bar / Club'),
    ('SHOPPING', 'Shopping'),
)

RESTAURANT_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)
因此,在django admin中,相应的Place表单将具有下拉菜单,可选择“餐厅、酒吧、俱乐部”,还有另一个字段称为“餐厅格式”

验证应确保如果第一次下拉设置为“餐厅”,则餐厅_字段不能为空

我正在尝试这样的事情:

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')
但是得到这个错误:

异常类型:KeyError 异常值:
地点类型


异常位置:/place/admin.py在clean中,第27行

我想我用这个clean例程得到了它:

def clean(self):
    cleaned_data = self.cleaned_data
    place_type = cleaned_data.get("place_type")
    restaurant_format = cleaned_data.get("restaurant_format")

    if place_type == 'RESTAURANT':
        if self.cleaned_data['restaurant_format'] is None:
            raise forms.ValidationError('For a restaurant you must choose a restaurant format')

    # Always return the full collection of cleaned data.
    return cleaned_data