我正在使用django-custom-user通过电子邮件登录。我有2个模型CustomUser和ClientData:
models.py
class CustomUser(AbstractEmailUser):
first_name = models.CharField(max_length=200, blank=True, null=True, default=None)
last_name = models.CharField(max_length=200, blank=True, null=True, default=None)
phone = models.CharField(max_length=20, blank=True, null=True, default=None)
class ClientData(models.Model):
user = models.OneToOneField(CustomUser)
company = models.CharField(max_length=200, blank=True, null=True, default=None)
bank_account = models.CharField(max_length=25, blank=True, null=True, default=None)
我正在尝试使用这两种型号制作注册表格,我已设法做到这一点,我也做了一个干净的密码功能,一切正常,但当我故意给出2个不同的密码时,我得到:
'ValidationError' object has no attribute 'get'
forms.py
class UserRegistrationForm(forms.ModelForm):
email = forms.EmailField(required=True, max_length=150)
first_name = forms.CharField(required=True, max_length=100)
last_name = forms.CharField(required=True, max_length=100)
password1 = forms.CharField(required=True, label='Password', max_length=100, widget=forms.PasswordInput())
password2 = forms.CharField(required=True, label='Confirm Password', max_length=100, widget=forms.PasswordInput())
phone = forms.CharField(required=True, max_length=20)
class Meta:
model = CustomUser
fields = ['email', 'first_name', 'last_name', 'password1', 'password2', 'phone']
def clean(self):
cleaned_data = super(UserRegistrationForm, self).clean()
password1 = cleaned_data.get('password1')
password2 = cleaned_data.get('password2')
if password1 != password2:
return forms.ValidationError('Password did not match.')
return cleaned_data
class UserDataRegistrationForm(forms.ModelForm):
class Meta:
model = ClientData
fields = ['company', 'bank_account']
这是我所做的观点:
views.py
def register(request):
data = dict()
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
data_form = UserDataRegistrationForm(request.POST)
if user_form.is_valid() * data_form.is_valid():
cd_user = user_form.cleaned_data
cd_data = data_form.cleaned_data
first_name = cd_user['first_name']
last_name = cd_user['last_name']
email = cd_user['email']
password = cd_user['password1']
phone = cd_user['phone']
company = cd_data['company']
bank_account = cd_data['bank_account']
new_user = CustomUser.objects.create_user(email, password)
ClientData.objects.create(user=new_user, company=company, bank_account=bank_account)
new_user.first_name = first_name
new_user.last_name = last_name
new_user.phone = phone
new_user.company = company
new_user.bank_account = bank_account
new_user.save()
else:
user_form = UserRegistrationForm()
data_form = UserDataRegistrationForm()
data['user_form'] = user_form
data['data_form'] = data_form
return render(request, 'registration/register.html', data)
为什么我会收到此错误?
答案 0 :(得分:4)
你不应该返回验证错误,你应该提出它们。
if password1 != password2:
raise forms.ValidationError('Password did not match.')