9

私はクリーンメソッドでこのようなことをしてきました:

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 つしか発生させないことを意味します。フォームがこれらのエラーの両方を発生させる方法はありますか?

編集#1:上記の解決策は素晴らしいですが、次のようなシナリオでも機能するものが大好きです:

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()

FooAddForm は ModelForm であり、エラーを引き起こす可能性のある一意の制約があります。誰かがそのようなことを知っていれば、それは素晴らしいことです...

4

4 に答える 4

18

ドキュメントから:

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
于 2010-01-22T13:41:41.747 に答える
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)
于 2010-01-22T12:59:03.393 に答える
3

エラー メッセージを特定のフィールドではなくフォームに添付したい場合は、次の__all__ようにキー " "を使用できます。

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

また、Django のドキュメントでは次のように説明されていますself._errorsErrorListいずれの場合も、問題のフィールド名のリストにエラー メッセージを追加すると、フォームが表示されたときに表示されます。

于 2010-03-09T00:49:50.067 に答える