· 4 years ago · Jul 23, 2021, 06:06 PM
1from django import forms
2from .models import MyUser
3
4
5class RegisterForm(forms.ModelForm):
6 first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
7 last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
8 username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
9 password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
10 password_confirmation = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
11 email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}))
12
13 class Meta:
14 model = MyUser
15 fields = ['first_name', 'last_name', 'username', 'email', 'password']
16
17
18 def clean(self):
19 cleaned_data = super().clean()
20 first_name = self.cleaned_data.get("first_name") or ''
21 last_name = self.cleaned_data.get("last_name") or ''
22 username = self.cleaned_data.get("username") or ''
23 password = self.cleaned_data.get("password") or ''
24 password_confirmation = self.cleaned_data.get("password_confirmation") or ''
25 email = self.cleaned_data.get("email") or ''
26
27 if not len(first_name) or not len(last_name):
28 raise forms.ValidationError("You should provide first and last name!")
29 if not len(username):
30 raise forms.ValidationError("You should provide some username!")
31 if not len(password) or not len(password_confirmation) or len(password) < 8:
32 raise forms.ValidationError("Password must be 8 characters minimum")
33 if not len(email):
34 raise forms.ValidationError("You should provide some email!")
35 if password != password_confirmation:
36 raise forms.ValidationError("Passwords don't match!")
37
38
39 def clean_first_name(self):
40 first_name = self.cleaned_data.get("first_name")
41 return first_name.capitalize()
42
43 def clean_last_name(self):
44 last_name = self.cleaned_data.get("last_name")
45 return last_name.capitalize()
46
47 def clean_email(self):
48 email = self.cleaned_data.get('email')
49 if '@gmail.com' not in email:
50 raise forms.ValidationError("Email must be 'gmail'.")
51 return email