2009-06-13 6 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のadminに、Placeの対応するフォームは、「レストラン、バー、クラブ」などの選択肢がプルダウンメニューを持っていますし、「restaurant_format」と呼ばれる別のフィールドがあります。

最初のプルダウンが「レストラン」に設定されている場合、restaurant_fieldをnullにすることはできません。

私はこのような何かしようとしています:

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できれいな、行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