如何验证客户年龄是否大于等于18岁,验证字段的正确方法是什么

2024-04-26 21:48:07 发布

您现在位置:Python中文网/ 问答频道 /正文

检查客户年龄是否大于等于18岁的最佳方法是什么?字段的最佳验证方法是什么!你知道吗

我试过一些不同的方法,但都有错误!你知道吗

我在这个网站上或者通过逆向工程Django的UserCreationForm找到了大多数实现

我这样做是“正确的”,但我遗漏了什么,还是有更好的方法?你知道吗

登记表

class AccountCreationForm(forms.ModelForm):
    username = forms.CharField(
        label='Username',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Enter username',
                'id': 'registerUsernameInput'
            },
        ),
    )
    email = forms.EmailField(
        label='Email',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Enter email',
                'id': 'registerEmailInput'
            },
        ),
    )
    password1 = forms.CharField(
        label='Password',
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Enter Password',
                'id': 'registerPassword1Input'
            },
        ),
    )
    password2 = forms.CharField(
        label='Confirm Password',
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': 'Confirm Password',
                'id': 'registerPassword2Input'
            },
        ),
    )
    date_born = forms.DateField(
        widget=forms.SelectDateWidget(
            years=[x for x in range(1940,timezone.now().date().year + 1)],
            attrs={
                'class': 'form-control',
            }
        )
    )

    class Meta:
        model = Account
        fields = ['username', 'email', 'password1', 'password2', 'date_born']

    def save(self, commit=True):
        user = super(AccountCreationForm, self).save(commit=False)
        user.username = self.cleaned_data.get('username')
        user.email = self.clean_email()
        user.password = self.clean_password2()
        user.date_born = self.clean_date_born()

        if commit:
            user.save()
        return user

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if not password2:
            raise ValidationError("You must confirm your password")
        if password1 != password2:
            raise ValidationError("Your passwords do not match")
        return password2

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if Account.objects.filter(email=email).exists():
            raise ValidationError('Email already exists')
        return email

    def clean_date_born(self):
        date_born = self.cleaned_data.get('date_born')
        if timezone.now().date() - date_born < timezone.timedelta(6574):
            raise ValidationError('You are under 18.')
        return date_born

注册视图

def register_view(request):

    # Redirect the user if already logged in
    if request.user.is_authenticated:
        return redirect('main:homepage')

    if request.method == 'GET':
        form = AccountCreationForm()
        return render(request, 'main/register.html', {'title': 'Register', 'form': form})

    if request.method == 'POST':
        form = AccountCreationForm(request.POST)
        if form.is_valid:   
            user = form.save()
            login(request, user)
            return redirect('main:homepage')


        messages.error(request, 'Form not valid') 
        return redirect('main:register')


Tags: selfformcleandatereturnifemailrequest
1条回答
网友
1楼 · 发布于 2024-04-26 21:48:07

如果您想验证模型的字段,那么可以使用验证器。 https://docs.djangoproject.com/en/2.2/ref/validators/

def validate_age(age):  
    if age <= 18:  
        raise ValidationError(_('%(age) should be more than 18'), 
        params= {'age':age},) 

或者,如果要验证表单字段,则可以使用以下数据: 在你的表单.py在类中可以定义函数:

def clean_fieldname(self):  
    field_content = self.cleaned_data['field_name']  
    #validate the field here and raise Validation Error if required  
    return the field_content 

根据我的建议,表单级别的验证要好得多。你知道吗

相关问题 更多 >