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 关注
- 128 浏览
添加回答
举报