0

フィールドA、B、Cを持つDjangoフォーム-XYZがあるとしましょう。フィールドBはユーザー名フィールドで、特定のユーザー名が既に存在する場合、検証エラーが発生し、メッセージが返されます。それに伴い、自動提案されたユーザー名辞書をテンプレートに送信したいと考えています。私の理解では、フィールド エラーと非フィールド エラーとしてのみ送信できます。

def clean_B(self):
        B = self.cleaned_data['B']
        if address.objects.filter(B=B).exists():
            raise forms.ValidationError("Username already exists")
        return B

Form.add_error() を使用して別のエラーを追加しようとしましたが、Django はフィールドごとの単一の辞書または Non_field エラーで複数のエラーを許可しません。

これどうやってするの?

ありがとう!

4

1 に答える 1

0

django messages frameworkユーザーへの提案とともにメッセージを表示するために使用できると思います。

from django.contrib import messages

...

def clean_B(self):
    B = self.cleaned_data['B']
    if address.objects.filter(B=B).exists():
        # In __init__ method of the form, you should store request as property
        messages.info(self.request, 'You should use another username, i.e. John')
        raise forms.ValidationError('Username already exists')
    return B

そして、テンプレートのどこかに、メッセージを出力します。

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
于 2016-02-14T01:31:41.713 に答える