Django form(表单)的验证以及错误提示


我想用Django的form实现一个简单的用户注册功能,目前完成的界面如下:

网站注册

我想完善的功能是当用户输入内容有误时,点击注册之后会在相应字段后面出现一个错误提示,就像Segmentfault的登录一样,密码错误下面会有简单的提示,如下:

带有错误提示的登路界面

我的部分代码如下,

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()
            # 重定向到首页(暂时没写)
        else:
            # 估计是这里的问题,但不知道怎么改正
            return redirect(reverse("accounts:signup"))

    else:
        signup_form = forms.SignupForm()

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

目前只是想简单验证两次输入密码是否一致,参考文档写了 clean_ 函数,但是没有成功。我猜测是views 中 signup_form.is_valid() 失败之后返回页面时需要带上form,但是不知道怎么做。

已经读了Django文档中Form部分的内容,但是仍旧找不到解决方法。

form web python django

一幽容翼一 10 years ago

lz可以参考这篇文章,变通实现这个功能
http://muilpin.blog.163.com/blog/static/165382936201221910158809/
ajax提交到后台,通过获取form.name.errors来确定name字段是否错误

天使D恶魔 answered 10 years ago


Your Answer