django 用户创建表单需要 keyerror
django user creation form required keyerror
我制作了一个自定义注册表单,它继承自 UserCreationForm
。但是,当您尝试提交时,其中一个字段为空,我得到一个 KeyError
必填项。
这似乎发生在 django 源代码的某个地方,但我很确定它是因为我的自定义清理方法。
表格:
class RegistrationForm(UserCreationForm):
"""
edit the User Registration form to add an emailfield
"""
class Meta:
model = User
fields = ('username', 'password1', 'password2')
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
#add custom errormessages
self.fields['username'].error_messages = {
'invalid': 'Invalid username'
}
self.fields['password2'].label = "Confirm Password"
#make sure username is lowered and unique
def clean_username(self):
username = self.cleaned_data.get('username')
try:
User.objects.get(username__iexact=username)
raise forms.ValidationError("This username is already in use.")
except User.DoesNotExist:
pass
return username
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
if commit:
user.save()
return user
错误日志http://pastebin.com/8Y6Tp7Rw
注意:我使用的是django 1.8
您似乎已经更改了 'username' 字段的原始错误消息(您不是添加,而是覆盖):
#add custom errormessages
self.fields['username'].error_messages = {
'invalid': 'Invalid username'
}
因此,当您将用户名留空时,它无法找到密钥 'required'。
您正在用您自己的字典替换所有 'username' 字段 error_messages 字典。相反,您应该使用您的自定义消息更新 error_messages 字典,如下所示:
self.fields['username'].error_messages.update({
'invalid': 'Invalid username'
})
我制作了一个自定义注册表单,它继承自 UserCreationForm
。但是,当您尝试提交时,其中一个字段为空,我得到一个 KeyError
必填项。
这似乎发生在 django 源代码的某个地方,但我很确定它是因为我的自定义清理方法。
表格:
class RegistrationForm(UserCreationForm):
"""
edit the User Registration form to add an emailfield
"""
class Meta:
model = User
fields = ('username', 'password1', 'password2')
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
#add custom errormessages
self.fields['username'].error_messages = {
'invalid': 'Invalid username'
}
self.fields['password2'].label = "Confirm Password"
#make sure username is lowered and unique
def clean_username(self):
username = self.cleaned_data.get('username')
try:
User.objects.get(username__iexact=username)
raise forms.ValidationError("This username is already in use.")
except User.DoesNotExist:
pass
return username
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
if commit:
user.save()
return user
错误日志http://pastebin.com/8Y6Tp7Rw
注意:我使用的是django 1.8
您似乎已经更改了 'username' 字段的原始错误消息(您不是添加,而是覆盖):
#add custom errormessages
self.fields['username'].error_messages = {
'invalid': 'Invalid username'
}
因此,当您将用户名留空时,它无法找到密钥 'required'。
您正在用您自己的字典替换所有 'username' 字段 error_messages 字典。相反,您应该使用您的自定义消息更新 error_messages 字典,如下所示:
self.fields['username'].error_messages.update({
'invalid': 'Invalid username'
})