django表单字段验证和错误显示

时间:2015-01-07 14:07:06

标签: python django forms

我想制作一个注册页面,如:

enter image description here

当用户点击注册时,我想检查两个密码是否相同,如果没有,请在“确认密码”后给出错误信息。这是我的代码:

forms.py

class SignupForm(forms.Form):
    username = forms.CahrField(
        label=_("username"),
        max_length=30,
    )

    email = forms.EmailField(label=_('email'),)
    password_1 = forms.CharField(
        label=_("password"),
        widget=forms.PasswordInput,
    )
    password_2 = forms.CharField(
        label=_("password_confirmed"),
        widget=forms.PasswordInput,
    )

    def clean_password_2(self):
        password_1 = self.cleaned_data.get("password_1")
        password_2 = self.cleaned_data.get("password_2")
        if password_1 and password_2 and password_1 != password_2:
            raise forms.ValidationError(_('password confirm failed'))
        return password_2 

signup.html

<form method="post" action="{% url 'accounts:signup_post' %}">
    {% csrf_token %}
    <table>
    {% for field in form %}
        <tr>
            <td>{{ field.label_tag }}</td>
            <td>{{ field }}</td>
            <td>{{ field.errors }}</td>
        </tr>
    {% endfor %}
    </table>

    <input type='submit' id="submit" value={% trans "signup" %}>
    <a href="{% url 'accounts:login' %}">{% trans "Already have accounts?" %}</a>
</form> 

views.py

def signup_post(request):
    if request.method == 'POST':
        signup_form = forms.SignupForm(request.POST)

        if signup_form.is_valid():
            signup_info = signup_form.cleaned_data
            username = signup_info['username']
            email = signup_info['email']
            password = signup_info['password_1']
            user = User.objects.create_user(
                username=username,
                email=email,
                password=password)
            user.save()
            # redirect to main page(not written so far)
        else:
            # I guess something wrong here, but no idea how to fix it.
            return redirect(reverse("accounts:signup"))

    else:
        signup_form = forms.SignupForm()

    return render(reverse("accounts:signup"), {'form': signup_form}) 

任何人都可以帮助我吗? 谢谢!

2 个答案:

答案 0 :(得分:2)

您的重定向呼叫不会显示错误,因为它已丢失了它的上下文。它应该足以不重定向,而是打印错误以进行日志记录。

而不是:

return redirect(reverse("accounts:signup"))

尝试:

print "Invalid Registration Attempt: user:{0} email:{1}".format(username, email)

当表单在呈现时出现在上下文中时,将显示错误:

return render(reverse("accounts:signup"), {'form': signup_form}) 

答案 1 :(得分:2)

您应该完全放弃第一个else条款。如果表单无效,则不应重定向,而应转到最终render调用,该调用会重新显示表单以及错误。