2010-01-22 4 views
9
내가 깨끗한 방법으로이 같은 일을 봤는데

제기에 대해 질문 :장고 : 형태의 깨끗한() 메소드를 오버라이드 (override) - 오류

if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: 
     raise forms.ValidationError('The type and organization do not match.') 
if self.cleaned_data['start'] > self.cleaned_data['end']: 
     raise forms.ValidationError('The start date cannot be later than the end date.') 

하지만 형태는 중 하나를 올릴 수 있다는 의미를 한 번에 이러한 오류. 양식에서 이러한 오류를 모두 제기 할 수있는 방법이 있습니까?

편집 # 1 : 위 대한 모든 솔루션은 중대하다,하지만 같은 시나리오에서 일하는 것이 뭔가를 사랑 : FooAddForm이 ModelForm이며 그 수도 고유 제한 조건을 가지고

if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: 
     raise forms.ValidationError('The type and organization do not match.') 
if self.cleaned_data['start'] > self.cleaned_data['end']: 
     raise forms.ValidationError('The start date cannot be later than the end date.') 
super(FooAddForm, self).clean() 

또한 오류를 유발합니다. 사람이 그런 뭔가 알고 있다면, 그 워드 프로세서

답변

17

... 좋은 것 :

https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

from django.forms.util import ErrorList 

def clean(self): 

    if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: 
    msg = 'The type and organization do not match.' 
    self._errors['type'] = ErrorList([msg]) 
    del self.cleaned_data['type'] 

    if self.cleaned_data['start'] > self.cleaned_data['end']: 
    msg = 'The start date cannot be later than the end date.' 
    self._errors['start'] = ErrorList([msg]) 
    del self.cleaned_data['start'] 

    return self.cleaned_data 
+0

매우 잘 작동합니다. 오류 메시지가 전체 양식이 아닌 필드에 첨부 된 것이 마음에 들지는 않지만 실제로는 이 방식으로 더 의미가 있습니다) 및 ModelForm 고유 제약 조건도 작동합니다. 그래서 나는 이것을 받아들입니다 - 감사합니다! :) –

7
errors = [] 
if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: 
     errors.append('The type and organization do not match.') 
if self.cleaned_data['start'] > self.cleaned_data['end']: 
    errors.append('The start date cannot be later than the end date.') 

if errors: 
    raise forms.ValidationError(errors) 
+0

Grrr ....이 +1을하려고했는데 우연히 두 번 클릭했는데 이제는 "투표가 너무 오래되었습니다"라고 표시됩니다. grrr ... 어쨌든, 좋은 답변 :)하지만 여전히 가지고 있습니다. 한 가지 문제가 있습니다 ... 고유 한 제약 조건을 확인하는 것이 중요하지만 ModelForm에서 하나의 깨끗한 메서드가 있습니다. 그렇다면 다음을 수행하십시오. 오류 인 경우 : raise forms.ValidationError (errors) super (CompetitionAddForm, self). clean() 다음 중 하나가 내 오류 또는 고유 한 제약 조건 오류 : -/ –

3

당신이 오류 메시지에 첨부 할 것을 원하는 경우 특정 필드가 아닌 양식 인 경우 다음과 같이 키 "__all__"을 사용할 수 있습니다.

msg = 'The type and organization do not match.' 
self._errors['__all__'] = ErrorList([msg]) 

또한 Django 문서에서 설명하는 것처럼 "특정 필드에 새 오류를 추가하려면 키가 이미 self._errors에 있는지 확인해야합니다. 그렇지 않은 경우 빈 ErrorList 인스턴스를 들고 지정된 키에 대한 새 항목을 만듭니다. 두 경우 모두 문제의 필드 이름 목록에 오류 메시지를 추가 할 수 있으며 양식이 표시 될 때 오류 메시지가 표시됩니다. "

3

이전 게시물이지만 코드가 적게 사용하려면 add_error() . 오류 메시지를 추가하는 방법은 내가 사용하는 경우 표시 할 @의 kemar의 답변을 확장하고있다 :. 자동 cleaned_data 사전에서 필드를 제거

add_error()

, 당신은 수동으로 삭제 해달라고을 은 또한 사용할 아무것도 가져올 필요 없다 이

documentation is here

def clean(self): 

    if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: 
    msg = 'The type and organization do not match.' 
    self.add_error('type', msg) 

    if self.cleaned_data['start'] > self.cleaned_data['end']: 
    msg = 'The start date cannot be later than the end date.' 
    self.add_error('start', msg) 

    return self.cleaned_data 
관련 문제