次の方法で form.clean() にカスタム動作を追加できます。
class YourForm(forms.Form):
# Everything as before.
...
def clean_name(self):
data = self.cleaned_data['name']
if data.strip() == '':
raise forms.ValidationError(u"You must provide more than just whitespace.")
# Always return the cleaned data, whether you have changed it or
# not.
return data
ただし、このタイプの検証を自動的に取得するタイプのフィールドを作成する場合は、次のように新しいクラスを追加します
class NoSpacesCharField(forms.CharField):
def validate(self, value):
# Use the parent's handling of required fields, etc.
super(NoSpacesCharField, self).validate(value)
if value.strip() == '':
raise ValidationError(u"You must provide more than just whitespace.")
次に、NoSpacesCharField
通常は forms.CharField を使用するのと同じように使用します。
私は現在、このコードをテストする立場にないので、奇妙なねじれがあるかもしれませんが、ほとんどの場合はそこに到達するはずです. Django でのフォーム検証の詳細については、https: //docs.djangoproject.com/en/dev/ref/forms/validation/ を参照してください。