【发布时间】:2021-04-11 20:39:31
【问题描述】:
我是 Django 的新手,我有一个注册表单,如果我填写所有字段并且当我没有填写所有字段时,一切正常。但是,当我提交一个没有用户名字段的表单时,我得到一个“键错误”而不是“此字段是必需的”异常,因为我已声明该字段是表单类所必需的。
forms.py
class UserRegistration(forms.ModelForm):
first_name = forms.CharField(label='First Name', max_length=50)
last_name = forms.CharField(label='Last Name', max_length=50)
username = forms.CharField(label='Username', max_length=50)
email = forms.EmailField(label='Email', max_length=50)
password = forms.CharField(label='Password', widget=forms.PasswordInput, max_length=50, validators = [validators.MinLengthValidator(6)])
password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput, max_length=50)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2')
def clean_username(self):
username = self.cleaned_data['username']
email = self.cleaned_data['email']
if username and User.objects.filter(username=username).exclude(email=email).count():
raise forms.ValidationError('This username address is already in use.')
return username
def clean_email(self):
email = self.cleaned_data['email']
username = self.cleaned_data['username']
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError('This email address is already in use.')
return email
def clean_password(self):
password = self.cleaned_data['password']
if len(password) < 6:
raise forms.ValidationError("Password is too short")
return password
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
views.py
def register(request):
if request.method == 'POST':
form = UserRegistration(request.POST)
if form.is_valid():
new_user = form.save(commit=False)
new_user.set_password(
form.cleaned_data.get('password')
)
new_user.save()
return render(request, 'authapp/register_done.html')
else:
return render(request, 'authapp/register.html', {'form':form})
else:
form = UserRegistration()
context = {
"form": form
}
return render(request, 'authapp/register.html', context=context)
【问题讨论】:
-
添加完整的错误回溯
-
我添加了两张截图。
标签: python django django-views django-forms