Django:如何使用forms.ValidationError并在模板中显示消息

时间:2014-02-05 20:39:04

标签: python django django-forms django-templates

下面我展示了为表单创建自定义clean()的代码,并且(我认为)在必要时会引发适当的验证错误。我可以在模板中显示{{ form.errors }},这是一个dict,并且可以解析模板中的dict以使其显示正确的错误消息,但我的方法必定是错误的。所以我的问题是1)我应该在表单中更改ValidationError的实现吗? 2)如何在模板中最好地显示错误消息?

class ParticipantLoginForm(AuthenticationForm):
    password = forms.CharField(label='Password', widget=forms.PasswordInput)
    passpin = forms.CharField(label='PIN', widget=forms.PasswordInput)

    error_messages = {
        'email_unknown': 'The email credential is unknown.',
        'invalid_pass': 'Invalid password or PIN',
        'inactive': 'This account is inactive',
    }

    def clean(self):
        email = self.cleaned_data.get('username')  # because this is in settings
        password = self.cleaned_data.get('password')
        passpin = self.cleaned_data.get('passpin')

        if email and password and passpin:
            self.user_cache = authenticate(
                email=email,
                password=password,
                passpin=passpin,
            )

            if self.user_cache is None:
                try:
                    participant = Participant.objects.get(email=email)
                except Participant.DoesNotExist:
                    raise forms.ValidationError(
                        self.error_messages['email_unknown'],
                        code='email_unknown',
                        params={'email': self.username_field}
                    )

                if participant.password != password or participant.passpin != passpin:
                    raise forms.ValidationError(
                        self.error_messages['invalid_pass'],
                        code='invalid_pass',
                    )

            elif not self.user_cache.is_active:
                raise forms.ValidationError(
                    self.error_messages['inactive'],
                    code='inactive',
                )

        return self.cleaned_data

我的基本模板:

{% extends "base.html" %}    
{% block content %}
    <form action="" method="post">{% csrf_token %}
        {% for k, message in form.errors.items %}
            {{ message }}
        {% endfor %}
        {% for field in form %}
            {{ field.label_tag }} {{ field }} {{ field.errors }}
        {% endfor %}
        <p><input type="submit" value="Submit"></p>
    </form>
{% endblock %}

0 个答案:

没有答案