簡體   English   中英

有條件的 Django 表單驗證

[英]Conditional Django form validation

對於 Django 項目,我有一個自定義的 User 模型:

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布爾字段。 設置此復選框后,不得選中passwordpassword2字段,因為它們的內容(或沒有內容)無關緊要。 相反,當auto_password復選框未設置時,必須選中passwordpassword2

有沒有辦法在需要時選擇性地禁用 Django 表單檢查?

謝謝您的幫助。

你不能把它包含在你的邏輯中嗎?

if not cd['auto_password'] and (cd['password'] != cd['password2']):
    raise forms.ValidationError(_("Passwords don't match."))

您將其添加到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')

    def clean(self):
        data = super().clean()
        if not 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'),
        #  required=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')

    def clean(self):
        data = super().clean()
        manual = not data['auto_password']
        if manual and not data['password']:
            raise forms.ValidationError(_('Password is empty.'))
        if manual and data['password'] != data['password2']:
            raise forms.ValidationError(_('Passwords don't match.'))
        return data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM