2009-06-13 46 views
0

我想在django中进行“上下文”表单验证。考虑这种情况下: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管理,用于放置相应的形式将有下拉菜单中包含“餐厅,酒吧,俱乐部”的选择,有一个名为“restaurant_format”另一个领域。

验证应确保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

异常位置:/地点/管理。 py in clean,line 27

回答

0

我想我是用这个干净的路线工作的ine:

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