为什么我的django注册表没有通过is_valid()

时间:2016-01-06 18:34:19

标签: python django

我是Django的新手,并且正在学习如何构建寄存器视图的教程。我完全一样,但我的表单没有通过form.is_valid()。

这是我做的:

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

class Meta:
    model = User
    fields = ('username', 'email', 'password1', 'password2')

def save(self, commit=True):
    user = super(MyRegistrationForm, self).save(commit=False)
    user.email = self.cleaned_data['email']

    if commit:
        user.save()
    return user

views.py

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()
        return HttpResponseRedirect('/accounts/register_success')

    form = MyRegistrationForm()
    return render(request, 'register.html', {'form':form})

def register_success(request):
    return render(request, 'register_success.html')

register.html

{% extends "base.html" %}

{% block content %}

<h2>Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
{{ form }}

<input type="submit" value="Register" />

</form>

{% endblock %}

当我尝试在网页上注册新用户时,他们都没有通过。即使我使用用户名:testuser email:testuser@example.com密码:testuser123,也失败了。那有什么不对?

提前致谢!

1 个答案:

答案 0 :(得分:0)

您应该遵循正确的视图模式。将行form = MyRegistrationForm()放在else块中,然后页面本身会告诉您表单无效的原因。