Reputation: 54
Whats the best way to check if a clients age is >= 18 and whats the best validation method for the fields!
I have tried some different methods but all of them have errors!
Most of these implementations i have found them on this site or by reverse engineering the Django's UserCreationForm
Is this way that i am doing it the "correct" but i am missing something or there is a better way?
Register Form
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
Register 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')
Upvotes: 2
Views: 1371
Reputation: 3243
If you want to validate the fields of a model then you can use validators. 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},)
OR if you want to validate the form field then you can use cleaned_data like: In your forms.py inside the class you can define a function:
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
As per my recommendation validation at form level is much better.
Upvotes: 2