Added JSON validator to Attributes.
[philo.git] / contrib / waldo / forms.py
1 from datetime import date
2 from django import forms
3 from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
4 from django.contrib.auth.models import User
5 from django.core.exceptions import ValidationError
6 from django.utils.translation import ugettext_lazy as _
7 from philo.contrib.waldo.tokens import REGISTRATION_TIMEOUT_DAYS
8
9
10 LOGIN_FORM_KEY = 'this_is_the_login_form'
11 LoginForm = type('LoginForm', (AuthenticationForm,), {
12         LOGIN_FORM_KEY: forms.BooleanField(widget=forms.HiddenInput, initial=True)
13 })
14
15
16 class EmailInput(forms.TextInput):
17         input_type = 'email'
18
19
20 class RegistrationForm(UserCreationForm):
21         email = forms.EmailField(widget=EmailInput)
22         
23         def clean_username(self):
24                 username = self.cleaned_data['username']
25                 
26                 # Trivial case: if the username doesn't exist, go for it!
27                 try:
28                         user = User.objects.get(username=username)
29                 except User.DoesNotExist:
30                         return username
31                 
32                 if not user.is_active and (date.today() - user.date_joined.date()).days > REGISTRATION_TIMEOUT_DAYS and user.last_login == user.date_joined:
33                         # Then this is a user who has not confirmed their registration and whose time is up. Delete the old user and return the username.
34                         user.delete()
35                         return username
36                 
37                 raise ValidationError(_("A user with that username already exists."))
38         
39         def clean_email(self):
40                 if User.objects.filter(email__iexact=self.cleaned_data['email']):
41                         raise ValidationError(_('This email is already in use. Please supply a different email address'))
42                 return self.cleaned_data['email']
43         
44         def save(self):
45                 username = self.cleaned_data['username']
46                 email = self.cleaned_data['email']
47                 password = self.cleaned_data['password1']
48                 new_user = User.objects.create_user(username, email, password)
49                 new_user.is_active = False
50                 new_user.save()
51                 return new_user