|
| 1 | +from django import forms |
| 2 | +from django.contrib.auth.models import User |
| 3 | +from django.contrib.auth.forms import UserCreationForm |
| 4 | +from django.core.exceptions import ValidationError |
| 5 | + |
| 6 | + |
| 7 | +class UserLoginForm(forms.Form): |
| 8 | + """Form to log users in""" |
| 9 | + username = forms.CharField() |
| 10 | + password = forms.CharField(widget=forms.PasswordInput) |
| 11 | + |
| 12 | + |
| 13 | +class UserRegistrationForm(UserCreationForm): |
| 14 | + """Form to register new user""" |
| 15 | + password1 = forms.CharField( |
| 16 | + label="Password", widget=forms.PasswordInput) |
| 17 | + password2 = forms.CharField( |
| 18 | + label="Confirm Password", |
| 19 | + widget=forms.PasswordInput) |
| 20 | + |
| 21 | + class Meta: |
| 22 | + model = User |
| 23 | + fields = ['email', 'username', 'password1', 'password2'] |
| 24 | + |
| 25 | + def clean_email(self): |
| 26 | + email = self.cleaned_data.get('email') |
| 27 | + username = self.cleaned_data.get('username') |
| 28 | + if User.objects.filter(email=email).exclude(username=username): |
| 29 | + raise forms.ValidationError(u'Email address already exists') |
| 30 | + return email |
| 31 | + |
| 32 | + def clean_password2(self): |
| 33 | + password1 = self.cleaned_data.get('password1') |
| 34 | + password2 = self.cleaned_data.get('password2') |
| 35 | + |
| 36 | + if not password1 or not password2: |
| 37 | + raise ValidationError("Please confirm password.") |
| 38 | + |
| 39 | + if password1 != password2: |
| 40 | + raise ValidationError("Passwords must match.") |
| 41 | + |
| 42 | + return password2 |
0 commit comments