Python 创建自定义用户注册表单 Django

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20192144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:49:20  来源:igfitidea点击:

Creating Custom user registration form Django

pythondjango

提问by Liondancer

I am trying to create custom user registration forms in Django but I am getting the following error. Everything on my page displays correctly however I get the error.

我正在尝试在 Django 中创建自定义用户注册表单,但出现以下错误。我页面上的所有内容都显示正确,但出现错误。

Error:

错误:

Exception Type: KeyError
Exception Value:    'First name'

My form.py:

我的form.py:

from django import forms            
from django.contrib.auth.models import User   # fill in custom user info then save it 
from django.contrib.auth.forms import UserCreationForm      

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required = True)
    first_name = forms.CharField(required = False)
    last_name = forms.CharField(required = False)
    birtday = forms.DateField(required = False)



    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']
        user.first_name = self.cleaned_data['First name']
        user.last_name = self.cleaned_data['Last name']
        user.birthday = self.cleaned_data['Birthday']


        if commit:
            user.save()

        return user

My views.py

我的意见.py

from django.shortcuts import render
from django.http import HttpResponseRedirect    
from django.contrib import auth                 
from django.core.context_processors import csrf 
from forms import MyRegistrationForm

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)     # create form object
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')
    args = {}
    args.update(csrf(request))
    args['form'] = MyRegistrationForm()
    print args
    return render(request, 'register.html', args)

采纳答案by Aamir Adnan

Here is the problem, you are accessing fields by using label rather it should be accessed by form field name:

这是问题所在,您正在使用标签访问字段,而应通过表单字段名称访问它:

self.cleaned_data['First name']

should be

应该

self.cleaned_data['first_name']

Similarly last_nameand birthday.

同样last_namebirthday