Revision 890b0eaf astakos/im/forms.py

b/astakos/im/forms.py
33 33

  
34 34
from django import forms
35 35
from django.utils.translation import ugettext as _
36
from django.contrib.auth.forms import UserCreationForm
36 37
from django.conf import settings
37 38
from hashlib import new as newhasher
38 39

  
39 40
from astakos.im.models import AstakosUser
41
from astakos.im.util import get_or_create_user
40 42

  
41
class RegisterForm(forms.Form):
42
    username = forms.CharField(widget=forms.widgets.TextInput())
43
    email = forms.EmailField(widget=forms.TextInput(),
44
                             label=_('Email address'))
45
    first_name = forms.CharField(widget=forms.TextInput(),
46
                                label=u'First Name', required=False)
47
    last_name = forms.CharField(widget=forms.TextInput(),
48
                                label=u'Last Name', required=False)
49
    
50
    def __init__(self, *args, **kwargs):
51
        super(forms.Form, self).__init__(*args, **kwargs)
52
    
53
    def clean_username(self):
54
        """
55
        Validate that the username is alphanumeric and is not already
56
        in use.
57
        
58
        """
43
class UniqueUserEmailField(forms.EmailField):
44
    """
45
    An EmailField which only is valid if no User has that email.
46
    """
47
    def validate(self, value):
48
        super(forms.EmailField, self).validate(value)
59 49
        try:
60
            user = AstakosUser.objects.get(username__iexact=self.cleaned_data['username'])
50
            AstakosUser.objects.get(email = value)
51
            raise forms.ValidationError("Email already exists")
52
        except AstakosUser.MultipleObjectsReturned:
53
            raise forms.ValidationError("Email already exists")
61 54
        except AstakosUser.DoesNotExist:
62
            return self.cleaned_data['username']
63
        raise forms.ValidationError(_("A user with that username already exists."))
55
            pass
64 56

  
65
class LocalRegisterForm(RegisterForm):
66
    """ local signup form"""
67
    password = forms.CharField(widget=forms.PasswordInput(render_value=False),
68
                                label=_('Password'))
69
    password2 = forms.CharField(widget=forms.PasswordInput(render_value=False),
70
                                label=_('Confirm Password'))
57
class ExtendedUserCreationForm(UserCreationForm):
58
    """
59
    Extends the built in UserCreationForm in several ways:
71 60
    
72
    def __init__(self, *args, **kwargs):
73
        super(LocalRegisterForm, self).__init__(*args, **kwargs)
61
    * Adds an email field, which uses the custom UniqueUserEmailField,
62
      that is, the form does not validate if the email address already exists
63
      in the User table.
64
    * The username field is generated based on the email, and isn't visible.
65
    * first_name and last_name fields are added.
66
    * Data not saved by the default behavior of UserCreationForm is saved.
67
    """
68
    
69
    username = forms.CharField(required = False, max_length = 30)
70
    email = UniqueUserEmailField(required = True, label = 'Email address')
71
    first_name = forms.CharField(required = False, max_length = 30)
72
    last_name = forms.CharField(required = False, max_length = 30)
74 73
    
75
    def clean_username(self):
74
    def __init__(self, *args, **kwargs):
76 75
        """
77
        Validate that the username is alphanumeric and is not already
78
        in use.
79
        
76
        Changes the order of fields, and removes the username field.
80 77
        """
81
        try:
82
            user = AstakosUser.objects.get(username__iexact=self.cleaned_data['username'])
83
        except AstakosUser.DoesNotExist:
84
            return self.cleaned_data['username']
85
        raise forms.ValidationError(_("A user with that username already exists."))
78
        super(UserCreationForm, self).__init__(*args, **kwargs)
79
        self.fields.keyOrder = ['email', 'first_name', 'last_name',
80
                                'password1', 'password2']
86 81
    
87
    def clean(self):
82
    def clean(self, *args, **kwargs):
83
        """
84
        Normal cleanup + username generation.
88 85
        """
89
        Verifiy that the values entered into the two password fields
90
        match. Note that an error here will end up in
91
        ``non_field_errors()`` because it doesn't apply to a single
92
        field.
86
        cleaned_data = super(UserCreationForm, self).clean(*args, **kwargs)
87
        if cleaned_data.has_key('email'):
88
            #cleaned_data['username'] = self.__generate_username(
89
            #                                            cleaned_data['email'])
90
            cleaned_data['username'] = cleaned_data['email']
91
        return cleaned_data
93 92
        
93
    def save(self, commit=True):
94 94
        """
95
        if 'password' in self.cleaned_data and 'password2' in self.cleaned_data:
96
            if self.cleaned_data['password'] != self.cleaned_data['password2']:
97
                raise forms.ValidationError(_("The two password fields didn't match."))
98
        return self.cleaned_data
95
        Saves the email, first_name and last_name properties, after the normal
96
        save behavior is complete.
97
        """
98
        user = super(UserCreationForm, self).save(commit)
99
        if user:
100
            kwargs = {}
101
            for field in self.fields:
102
                if hasattr(AstakosUser(), field):
103
                    kwargs[field] = self.cleaned_data[field]
104
            user = get_or_create_user(username=self.cleaned_data['email'], **kwargs)
105
        return user
99 106

  
100
class InvitedRegisterForm(RegisterForm):
107
class InvitedExtendedUserCreationForm(ExtendedUserCreationForm):
108
    """
109
    Subclass of ``RegistrationForm`` for registring a invited user. Adds a
110
    readonly field for inviter's name. The email is also readonly since
111
    it will be the invitation username.
112
    """
101 113
    inviter = forms.CharField(widget=forms.TextInput(),
102 114
                                label=_('Inviter Real Name'))
103 115
    
......
105 117
        super(RegisterForm, self).__init__(*args, **kwargs)
106 118
        
107 119
        #set readonly form fields
108
        self.fields['username'].widget.attrs['readonly'] = True
109 120
        self.fields['inviter'].widget.attrs['readonly'] = True
110 121

  
111
class InvitedLocalRegisterForm(LocalRegisterForm, InvitedRegisterForm):
112
    pass
122
class ProfileForm(forms.ModelForm):
123
    """
124
    Subclass of ``ModelForm`` for permiting user to edit his/her profile.
125
    Most of the fields are readonly since the user is not allowed to change them.
126
    
127
    The class defines a save method which sets ``is_verified`` to True so as the user
128
    during the next login will not to be redirected to profile page.
129
    """
130
    class Meta:
131
        model = AstakosUser
132
        exclude = ('groups', 'user_permissions')
133
    
134
    def __init__(self, *args, **kwargs):
135
        super(ProfileForm, self).__init__(*args, **kwargs)
136
        instance = getattr(self, 'instance', None)
137
        ro_fields = ('username','date_joined', 'updated', 'auth_token',
138
                     'auth_token_created', 'auth_token_expires', 'invitations',
139
                     'level', 'last_login', 'email', 'is_active', 'is_superuser',
140
                     'is_staff')
141
        if instance and instance.id:
142
            for field in ro_fields:
143
                if isinstance(self.fields[field].widget, forms.CheckboxInput):
144
                    self.fields[field].widget.attrs['disabled'] = True
145
                self.fields[field].widget.attrs['readonly'] = True
146
    
147
    def save(self, commit=True):
148
        user = super(ProfileForm, self).save(commit=False)
149
        user.is_verified = True
150
        if commit:
151
            user.save()
152
        return user
153

  
113 154

  
114
class LoginForm(forms.Form):
115
    username = forms.CharField(widget=forms.widgets.TextInput())
116
    password = forms.CharField(widget=forms.PasswordInput(render_value=False),
117
                                label=_('Password'))
155
class FeedbackForm(forms.Form):
156
    """
157
    Form for writing feedback.
158
    """
159
    feedback_msg = forms.CharField(widget=forms.Textarea(),
160
                                label=u'Message', required=False)
161
    feedback_data = forms.CharField(widget=forms.Textarea(),
162
                                label=u'Data', required=False)
163
    

Also available in: Unified diff