Completed
Push — master ( a5ee20...4f370a )
by Vijay
9s
created

PartnerForm.clean_contact_number()   A

Complexity

Conditions 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 13
rs 9.2
cc 4
1
from django import forms
2
from django.contrib.auth import get_user_model
3
from django.contrib.auth.forms import AuthenticationForm
4
from django.core.exceptions import ValidationError
5
from django.utils.translation import ugettext_lazy as _
6
7
from simplemathcaptcha.fields import MathCaptchaField
8
9
from wye.base.constants import ContactFeedbackType
10
11
from . import models
12
13
14
class UserAuthenticationForm(AuthenticationForm):
15
    username = forms.CharField(label=_("Email"), max_length=100, required=True)
16
    password = forms.CharField(label=_("Password"),
17
                               widget=forms.PasswordInput,
18
                               required=True)
19
20
21
class SignupForm(forms.ModelForm):
22
23
    def __init__(self, *args, **kwargs):
24
        super(SignupForm, self).__init__(*args, **kwargs)
25
        mandatory_field(self)
26
27
    mobile = forms.CharField(
28
        label=_("Mobile"),
29
        max_length=10,
30
        widget=forms.TextInput(
31
            attrs={'placeholder': 'Mobile'}
32
        )
33
    )
34
35
    def clean_mobile(self):
36
        mobile = self.cleaned_data['mobile']
37
        error_message = []
38
        if not mobile.isdigit():
39
            error_message.append(
40
                "Contact Number should only consist digits")
41
        if not len(mobile) == 10:
42
            error_message.append(
43
                "Contact Number should be of 10 digits")
44
45
        if error_message:
46
            raise ValidationError(error_message)
47
        return mobile
48
49
    class Meta:
50
        model = get_user_model()
51
        fields = ['first_name', 'last_name']
52
        widgets = {
53
            'first_name': forms.TextInput(
54
                attrs={'placeholder': 'First Name', 'autofocus': 'on'}),
55
            'last_name': forms.TextInput(
56
                attrs={'placeholder': 'Last Name'}),
57
        }
58
59
    def signup(self, request, user):
60
        profile = user.profile
61
        profile.mobile = self.cleaned_data['mobile']
62
        profile.save()
63
64
65
class UserProfileForm(forms.ModelForm):
66
    first_name = forms.CharField(label="First Name", max_length=50)
67
    last_name = forms.CharField(label="Last Name", max_length=50)
68
    queryset = models.UserType.objects.exclude(
69
        slug__in=['admin', 'lead', 'coordinator'])
70
    usertype = forms.ModelMultipleChoiceField(
71
        label="Usertype", queryset=queryset)
72
73
    def __init__(self, *args, **kwargs):
74
        super(UserProfileForm, self).__init__(*args, **kwargs)
75
        self.fields['first_name'].required = True
76
        self.fields['first_name'].initial = self.instance.user.first_name
77
        self.fields['last_name'].required = True
78
        self.fields['last_name'].initial = self.instance.user.last_name
79
        mandatory_field(self)
80
81
    def clean_interested_states(self):
82
        if ('tutor' in [u.slug for u in self.cleaned_data['usertype']]):
83
            if not self.cleaned_data['interested_states']:
84
                raise ValidationError('States field is mandatory')
85
        return self.cleaned_data['interested_states']
86
87
    def clean_github(self):
88
        if ('tutor' in [u.slug for u in self.cleaned_data['usertype']]):
89
            if not(
90
                ('github' in self.cleaned_data and
91
                    self.cleaned_data['github']) or
92
                ('linkedin' in self.cleaned_data and
93
                    self.cleaned_data['linkedin'])
94
            ):
95
                raise ValidationError(
96
                    'Github or LinkedIn field is mandatory')
97
        return self.cleaned_data['github']
98
99
    def clean_linkedin(self):
100
        if ('tutor' in [u.slug for u in self.cleaned_data['usertype']]):
101
            if not (
102
                ('github' in self.cleaned_data and
103
                    self.cleaned_data['github']) or
104
                ('linkedin' in self.cleaned_data and
105
                    self.cleaned_data['linkedin'])
106
            ):
107
                raise ValidationError(
108
                    'Github or LinkedIn field is mandatory')
109
        return self.cleaned_data['linkedin']
110
111
    def clean_interested_level(self):
112
        if ('tutor' in [u.slug for u in self.cleaned_data['usertype']]):
113
            if not self.cleaned_data['interested_level']:
114
                raise ValidationError(
115
                    'Interested workshop level field is mandatory')
116
        return self.cleaned_data['interested_level']
117
118
    def is_valid(self):
119
        return super(UserProfileForm, self).is_valid()
120
121
    def save(self, *args, **kwargs):
122
        self.instance.user.first_name = self.cleaned_data['first_name']
123
        self.instance.user.last_name = self.cleaned_data['last_name']
124
        self.instance.user.save()
125
        self.instance.save()
126
        return self.instance
127
128
    class Meta:
129
        model = models.Profile
130
        exclude = ('user', 'slug', 'interested_locations')
131
132
133
class ContactUsForm(forms.Form):
134
135
    name = forms.CharField(label='Your name*', required=True)
136
    email = forms.EmailField(label='Your email*', required=True)
137
    feedback_type = forms.ChoiceField(label='Feedback on*', required=True,
138
                                      choices=ContactFeedbackType.CHOICES)
139
    comments = forms.CharField(
140
        label='Comments*', required=True, widget=forms.Textarea)
141
    contact_number = forms.CharField(
142
        label='Your contact number', required=False)
143
    captcha = MathCaptchaField()
144
145
    def clean_contact_number(self):
146
        contact_number = self.cleaned_data['contact_number']
147
        error_message = []
148
        if not contact_number.isdigit():
149
            error_message.append(
150
                "Contact Number should only consist digits")
151
        if not len(contact_number) == 10:
152
            error_message.append(
153
                "Contact Number should be of 10 digits")
154
155
        if error_message:
156
            raise ValidationError(error_message)
157
        return contact_number
158
159
160
def mandatory_field(self):
161
    for v in filter(lambda x: x.required, self.fields.values()):
162
        v.label = str(v.label) + "*"
163
164
165
class PartnerForm(forms.Form):
166
    partner_choices = (
167
        ('profit', 'Profit making'),
168
        ('non-profit', "Non Profit"))
169
    org_name = forms.CharField(label='Organization Name*', required=True)
170
    org_url = forms.URLField(label='Organization Url*', required=True)
171
    partner_type = forms.ChoiceField(
172
        label='Type of organization*',
173
        required=True, choices=partner_choices)
174
    description = forms.CharField(
175
        label='Describe how your organization will help both of us *',
176
        required=True, widget=forms.Textarea)
177
    python_use = forms.CharField(
178
        label='Use of python in your organization ? *',
179
        required=True, widget=forms.Textarea)
180
    name = forms.CharField(label='Your Name*', required=True)
181
    email = forms.EmailField(label='Your email*', required=True)
182
    contact_number = forms.CharField(
183
        label='Your contact number', required=True)
184
185
    comments = forms.CharField(
186
        label='Comments*',
187
        required=True, widget=forms.Textarea)
188
189
    captcha = MathCaptchaField()
190
191
    def clean_contact_number(self):
192
        contact_number = self.cleaned_data['contact_number']
193
        error_message = []
194
        if not contact_number.isdigit():
195
            error_message.append(
196
                "Contact Number should only consist digits")
197
        if not len(contact_number) == 10:
198
            error_message.append(
199
                "Contact Number should be of 10 digits")
200
201
        if error_message:
202
            raise ValidationError(error_message)
203
        return contact_number
204