2009-06-13 10 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) 

그래서 장고 관리자에서, 장소에 대한 해당 양식은 "레스토랑, 바, 클럽"와 같은 선택과 풀다운 메뉴가되며, "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 in clean, line 27

답변

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