我正在尝试在Django中创建自定义用户注册表单,但是我收到以下错误。我页面上的所有内容都正确显示,但是我收到错误。
错误:
Exception Type: KeyError
Exception Value: 'First name'
我的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
我的views.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)
答案 0 :(得分:9)
问题是,您正在使用标签访问字段,而应该通过表单字段名称访问:
self.cleaned_data['First name']
应该是
self.cleaned_data['first_name']
同样last_name
和birthday
。