2009-06-13 79 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