对于Django项目,我有一个自定义的用户模型:
class User(AbstractUser):
username = None
email = models.EmailField(_('e-mail address'),
unique=True)
first_name = models.CharField(_('first name'),
max_length=150,
blank=False)
last_name = models.CharField(_('last name'),
max_length=150,
blank=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = UserManager()
def __str__(self):
return self.email
我正在创建一个新的用户注册表格:
class UserRegistrationForm(forms.ModelForm):
auto_password = forms.BooleanField(label=_('Generate password and send by mail'),
required=False,
initial=True)
password = forms.CharField(label=_('Password'),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_('Repeat password'),
widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'is_staff',
'is_superuser')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError(_("Passwords don't match."))
return cd['password2']
我的表单有一个auto_password
布尔字段。如果设置了此复选框,则不得选中password
和password2
字段,因为它们的内容(或没有内容(不重要。相反,如果未设置auto_password
复选框,则必须选中password
和password2
。
有没有一种方法可以在需要时选择性地禁用Django表单检查?
谢谢你的帮助。
您将其添加到clean
方法中的条件中:
class UserRegistrationForm(forms.ModelForm):
auto_password = forms.BooleanField(
label=_('Generate password and send by mail'),
required=False,
initial=True
)
password = forms.CharField(
label=_('Password'),
widget=forms.PasswordInput
)
password2 = forms.CharField(
label=_('Repeat password'),
widget=forms.PasswordInput
)
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'is_staff',
'is_superuser')
defclean(self):
data = super().clean()
ifnot data['auto_password']and data['password'] != data['password2']:
raise forms.ValidationError(_('Passwords don't match.'))
return data
因此,如果复选框被选中,not data['auto_password']
将返回False
,在这种情况下,data['password'] != data['password2']
的检查将不会运行,也不会引发ValidationError
。
您还可以删除required=True
属性,并通过检查其真实性来检查password
是否至少包含一个字符:
class UserRegistrationForm(forms.ModelForm):
auto_password = forms.BooleanField(
label=_('Generate password and send by mail'),
#norequired=True
initial=True
)
password = forms.CharField(
label=_('Password'),
widget=forms.PasswordInput
)
password2 = forms.CharField(
label=_('Repeat password'),
widget=forms.PasswordInput
)
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'is_staff',
'is_superuser')
defclean(self):
data = super().clean()
manual= not data['auto_password']
ifmanual and not data['password']:
raise forms.ValidationError(_('Password is empty.'))
ifmanualand data['password'] != data['password2']:
raise forms.ValidationError(_('Passwords don't match.'))
return data
难道不能将其包含在逻辑中吗?
if not cd['auto_password'] and (cd['password'] != cd['password2']):
raise forms.ValidationError(_("Passwords don't match."))