gpt4 book ai didi

python - 如何验证客户年龄是否 >= 18 以及验证字段的正确方法是什么

转载 作者:行者123 更新时间:2023-12-01 07:44:39 26 4
gpt4 key购买 nike

检查客户年龄是否 >= 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

注册 View

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')

最佳答案

如果您想验证模型的字段,则可以使用验证器。 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},)

或者,如果您想验证表单字段,则可以使用cleaned_data,例如:在类内的 forms.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

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

关于python - 如何验证客户年龄是否 >= 18 以及验证字段的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56518788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com