aboutsummaryrefslogtreecommitdiffstats
path: root/account/forms.py
blob: cb0b6b24b487ecd927fec7ceb09c19b36c3c5ea8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# -*- coding: utf-8 -*-

"""
account/forms.py for skaschool
"""

from django import forms
from django.forms.models import inlineformset_factory
from django.contrib.auth.models import User
from django.contrib.sites.models import Site, RequestSite
from django.utils.translation import ugettext_lazy as _

from registration.forms import RegistrationFormUniqueEmail
from captcha.fields import ReCaptchaField

from account.models import UserProfile, UserFile


class UserRegForm(RegistrationFormUniqueEmail):
    """
    based on 'django-registration' RegistrationFormUniqueEmail
    add fields 'realname', 'gender', 'institute' and 'captcha'
    """
    # XXX: keep consistent with GENDERS in 'models.UserProfile'
    GENDERS = UserProfile.GENDERS
    IDENTIFIES = UserProfile.IDENTIFIES
    realname = forms.CharField(max_length=30, label=_("Name"))
    gender = forms.ChoiceField(choices=GENDERS, label=_("Gender"))
    institute = forms.CharField(max_length=100, label=_("Institute"))
    identify = forms.ChoiceField(choices=IDENTIFIES, label=_("Identify"))
    captcha = ReCaptchaField(label=_("Captcha"),
            attrs={'theme': 'clean'})

    #def __init__(self, *args, **kw):
    #    super(UserRegForm, self).__init__(*args, **kw)
    #    # order form fields
    #    self.fields.keyOrder = [
    #            'username',
    #            'email',
    #            'password1',
    #            'password2',
    #            'realname',
    #            'gender',
    #            'institute',
    #            'identify',
    #    ]


class ResendEmailForm(forms.Form):
    """
    form used in ResendEmailView
    """
    username = forms.RegexField(regex=r'^[\w.@+-]+$',
                                max_length=30,
                                label=_("Username"),
                                error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
    is_update_email = forms.BooleanField(label=_("Is update email"),
            required=False, initial=False)
    email = forms.EmailField(label=_("E-mail"), required=False)

    def clean_username(self):
        username = self.cleaned_data.get('username', '')
        user = User.objects.filter(username=username)
        if not user:
            raise forms.ValidationError(_("Username not exists"), code='invalid')
        return username

    def clean(self):
        # if 'is_update_email' True, then email field is required
        is_update_email = self.cleaned_data.get('is_update_email', False)
        email = self.cleaned_data.get('email', '')
        if (is_update_email and (not email)):
            raise forms.ValidationError(_("Email is required"), code='required')
        return self.cleaned_data

    def update_email(self):
        # update User email if user provided a different email
        username = self.cleaned_data.get('username', '')
        email = self.cleaned_data.get('email', '')
        user = User.objects.get(username=username)
        if email:
            user.email = email
            user.save()

    def resend_email(self):
        # resend activation email
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(self.request)

        username = self.cleaned_data.get('username', '')
        user = User.objects.get(username=username)
        regprofile = user.registrationprofile_set.get(user=user)
        if not regprofile.activation_key_expired():
            regprofile.send_activation_email(site)


class UpdateProfileForm(forms.ModelForm):
    """
    ModelForm of 'UserProfile' used in 'UpdateProfileView'
    """
    # extra email field
    email = forms.EmailField(label=_("E-mail"))

    class Meta:
        model = UserProfile
        fields = (
            'user',
            'realname',
            'gender',
            'institute',
            'identify',
            'reason',
            'transcript',
            'supplement',
        )
        widgets = {
            'user': forms.HiddenInput,
        }

    def __init__(self, *args, **kwargs):
        super(UpdateProfileForm, self).__init__(*args, **kwargs)
        # reorder fields, append 'email' just after 'realname'
        self.fields.keyOrder = [
            'user',
            'realname',
            'email',
            'gender',
            'institute',
            'identify',
            'reason',
            'transcript',
            'supplement',
        ]

    def clean(self):
        """
        check if 'transcript' is needed and provided
        """
        form_data = self.cleaned_data
        user = form_data.get('user')
        profile = user.userprofile_set.get(user=user)
        profile.identify = form_data.get('identify', profile.identify)
        transcript = self.cleaned_data.get('transcript', False)
        if (profile.is_transcript_required() and (not transcript)):
            raise forms.ValidationError(_("Transcript is required."), code='required')
        # not save 'profile' here
        return self.cleaned_data


class UserFileForm(forms.ModelForm):
    """
    form of UserFile, empty_permitted=True
    """
    class Meta:
        model = UserFile

    def __init__(self, *args, **kwargs):
        super(UserFileForm, self).__init__(*args, **kwargs)
        self.empty_permitted = True


### formset ###
# UserFileFormSet: parent_model -> User
UserFileFormSet = inlineformset_factory(User,
        UserFile, form=UserFileForm,
        extra=1, can_delete=True)