0

ビューにエラーを表示することについて理解できなかった古い回答と例のみが見つかりました。

に何かがあるかどうかをチェックし、そうでない場合は a を発生させるclean_messageメソッドを myに作成しました。forms.pyself.messageValidationError

"""
Comment
"""
class CommentForm(forms.Form):
    """
    Comment field
    """
    comment = forms.CharField(
        widget = forms.Textarea(
            attrs = {
                'class': 'form-control',
                'rows': 2 
            }
        )
    )

    def clean_comment(self):
        if self.cleaned_data['comment'] is None:
            raise form.ValidationError({'comment': ['You must enter your comment'])

そして、これがビューファイルです。上記のように作成されたエラーを表示するには何が必要ですか?

<form action="comment" method="POST">
    {% csrf_token %}
    <div class="form-group">
        {{ form.comment.errors }}
        {{ form.comment }}
    </div>
    <div class="form-group">
        <input type="submit" value="Say it" class="btn btn-success"> 
    </div>
</form>

{{ form.errors }} の使用、反復、{{ form.non_field_errors }} などの使用を試みましたが、どれも機能しませんでした。どういうわけかフォームをリロードしていると思うので、メッセージは表示されません。

4

1 に答える 1

0

フォーム レベルでエラーを表示するには、次を使用するだけです{{ form.errors }}。しかし、フィールドレベルのエラーメッセージが必要なようです。そのためには、 clean メソッドを次のように変更する必要があります。

def clean_message(self):
    if not self.message:
        raise ValidationError({'message': ['You must enter your comment'])

このようにして、エラーは適切に設定されますfield.errors

于 2016-03-20T04:08:20.597 に答える