2 回答

TA貢獻1868條經驗 獲得超4個贊
您需要在表單中指定要包含的所有字段:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
password_confirm = forms.CharField(widget=forms.PasswordInput())
class Meta:
fields = ['email', 'password']
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get("password")
password_confirm = cleaned_data.get("password_confirm")
if password != password_confirm:
self.add_error('password_confirm', "Password does not match")
return cleaned_data
但請注意,您需要手動驗證字段是否與字段匹配password_confirmpassword

TA貢獻1836條經驗 獲得超5個贊
我以為密碼和確認密碼會默認存在。我說得對嗎?
不可以。A 具有基于您提供的模型構造 A 的邏輯。但它不會將用戶模型與另一個模型區別對待。如果指定 ,它將只創建一個包含該字段的表單,作為唯一的表單。ModelForm
Form
fields = ['email']
email
更糟糕的是,它不會創建正確的用戶對象,因為密碼應該被哈希化,你可以用?.set_password(...)
?方法 [Django-doc]?存儲哈希密碼。因此,我們可以創建一個如下所示的表單:
class UserCreateForm(forms.ModelForm):
? ? password = forms.CharField(
? ? ? ? label='Password',
? ? ? ? strip=False,
? ? ? ? widget=forms.PasswordInput()
? ? )
? ? def save(self, *args, **kwargs):
? ? ? ? self.instance.set_password(self.cleaned_data['password'])
? ? ? ? return super().save(*args, **kwargs)
? ??
? ? class Meta:
? ? ? ? model = get_user_model()
? ? ? ? fields = ['email']
如果要驗證密碼,則需要添加一些額外的邏輯:
from django.core.exceptions import ValidationError
class UserCreateForm(forms.ModelForm):
? ? password = forms.CharField(
? ? ? ? label='Password',
? ? ? ? strip=False,
? ? ? ? widget=forms.PasswordInput()
? ? )
? ? password2 = forms.CharField(
? ? ? ? label='Repeat password',
? ? ? ? strip=False,
? ? ? ? widget=forms.PasswordInput()
? ? )
? ? def clean(self, *args, **kwargs):
? ? ? ? cleaned_data = super().clean(*args, **kwargs)
? ? ? ? if cleaned_data['password'] != cleaned_data['password2']:
? ? ? ? ? ? raise ValidationError('Passwords do not match')
? ? ? ? return cleaned_data
? ? def save(self, *args, **kwargs):
? ? ? ? self.instance.set_password(self.cleaned_data['password'])
? ? ? ? return super().save(*args, **kwargs)
? ??
? ? class Meta:
? ? ? ? model = get_user_model()
? ? ? ? fields = ['email']
- 2 回答
- 0 關注
- 330 瀏覽
添加回答
舉報