我想在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管理员中,Place的相应表单将有下拉菜单,其中包含“餐厅,酒吧,俱乐部”等选项,还有另一个名为“restaurant_format”的字段。
如果第一个下拉列表设置为“restaurant”,则验证应确保restaurant_field不能为空。
我正在尝试这样的事情:
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_type
异常位置:/place/admin.py in clean,第27行
答案 0 :(得分:0)
我想我已经开始使用这个干净的例行程序了:
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