firstname和lastname没有以django形式显示

时间:2017-11-16 16:42:03

标签: python django

我试图创建一个包含以下信息(名字,姓氏,电子邮件,密码,密码确认)的注册表单,但是我没有得到名字和姓氏。到目前为止我只收到用户名,密码和密码确认。为了添加缺少的字段,我做错了什么?

forms.py

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, label='Fornavn', help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, label='Efternavn', help_text='Optional.')
    email = forms.EmailField(max_length=254, label='Email', help_text='Required. Inform a valid email address.')

class Meta:
    model = User
    fields = ('username', 'first_name', 'last_name', 'email')

register.html

{% for field in form %}
<div class="form-group">
     <label>{{ field.label }}</label>
     {% render_field field class="form-control" placeholder=field.help_text %}
</div>
{% endfor %}

views.py

def register(request):
    if request.user.is_authenticated():
        return redirect('/account/')
    context = {}
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('/account/')
    else:
        form = UserCreationForm()
    return render(request, 'register.html', {'form': form})

网址

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^register/$', views.register, name='register')

]

1 个答案:

答案 0 :(得分:5)

您的GET(和其他)请求正在传递UserCreationForm而不是SignUpForm

if request.method == "POST":
    ...
else:
    form = SignUpForm()