检查客户年龄是否大于等于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')
答案 0 :(得分:1)
如果要验证模型的字段,则可以使用验证器。 https://docs.djangoproject.com/en/2.2/ref/validators/
background: repeating-linear-gradient(
-55deg,
#222,
#222 10px,
#333 10px,
#333 20px
);
或者,如果您想验证表单字段,则可以使用cleaned_data,例如: 在类内的forms.py中,您可以定义一个函数:
def validate_age(age):
if age <= 18:
raise ValidationError(_('%(age) should be more than 18'),
params= {'age':age},)
根据我的建议,在表单级别的验证要好得多。