PartnerForm.clean_contact_number()   A
last analyzed

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
        self.fields['occupation'].required = True
80
        mandatory_field(self)
81
82
    def clean_interested_states(self):
83
        if ('tutor' in [u.slug for u in self.cleaned_data['usertype']]):
84
            if not self.cleaned_data['interested_states']:
85
                raise ValidationError('States field is mandatory')
86
        return self.cleaned_data['interested_states']
87
88
    def clean_github(self):
89
        if ('tutor' in [u.slug for u in self.cleaned_data['usertype']]):
90
            if not(
91
                ('github' in self.cleaned_data and
92
                    self.cleaned_data['github']) or
93
                ('linkedin' in self.cleaned_data and
94
                    self.cleaned_data['linkedin'])
95
            ):
96
                raise ValidationError(
97
                    'Github or LinkedIn field is mandatory')
98
        return self.cleaned_data['github']
99
100
    def clean_linkedin(self):
101
        if ('tutor' in [u.slug for u in self.cleaned_data['usertype']]):
102
            if not (
103
                ('github' in self.cleaned_data and
104
                    self.cleaned_data['github']) or
105
                ('linkedin' in self.cleaned_data and
106
                    self.cleaned_data['linkedin'])
107
            ):
108
                raise ValidationError(
109
                    'Github or LinkedIn field is mandatory')
110
        return self.cleaned_data['linkedin']
111
112
    def clean_interested_level(self):
113
        if ('tutor' in [u.slug for u in self.cleaned_data['usertype']]):
114
            if not self.cleaned_data['interested_level']:
115
                raise ValidationError(
116
                    'Interested workshop level field is mandatory')
117
        return self.cleaned_data['interested_level']
118
119
    def is_valid(self):
120
        return super(UserProfileForm, self).is_valid()
121
122
    def save(self, *args, **kwargs):
123
        self.instance.user.first_name = self.cleaned_data['first_name']
124
        self.instance.user.last_name = self.cleaned_data['last_name']
125
        self.instance.user.save()
126
        profile_form = super(UserProfileForm, self).save(commit=True)
127
        return profile_form
128
129
    class Meta:
130
        model = models.Profile
131
        exclude = ('user', 'slug', 'interested_locations')
132
        fields = (
133
            'first_name', 'last_name', 'mobile',
134
            'picture',
135
            'occupation', 'work_location',
136
            'work_experience', 'no_workshop', 'is_mobile_visible',
137
            'is_email_visible', 'enable_notifications', 'usertype',
138
            'interested_sections', 'interested_level', 'interested_states',
139
            'location', 'github', 'facebook', 'googleplus',
140
            'linkedin', 'twitter', 'slideshare')
141
142
143
class ContactUsForm(forms.Form):
144
145
    name = forms.CharField(label='Your name*', required=True)
146
    email = forms.EmailField(label='Your email*', required=True)
147
    feedback_type = forms.ChoiceField(label='Feedback on*', required=True,
148
                                      choices=ContactFeedbackType.CHOICES)
149
    comments = forms.CharField(
150
        label='Comments*', required=True, widget=forms.Textarea)
151
    contact_number = forms.CharField(
152
        label='Your contact number', required=False)
153
    captcha = MathCaptchaField()
154
155
    def clean_contact_number(self):
156
        contact_number = self.cleaned_data['contact_number']
157
        error_message = []
158
        if not contact_number.isdigit():
159
            error_message.append(
160
                "Contact Number should only consist digits")
161
        if not len(contact_number) == 10:
162
            error_message.append(
163
                "Contact Number should be of 10 digits")
164
165
        if error_message:
166
            raise ValidationError(error_message)
167
        return contact_number
168
169
170
def mandatory_field(self):
171
    for v in filter(lambda x: x.required, self.fields.values()):
172
        v.label = str(v.label) + "*"
173
174
175
class PartnerForm(forms.Form):
176
    partner_choices = (
177
        ('profit', 'Profit making'),
178
        ('non-profit', "Non Profit"))
179
    org_name = forms.CharField(label='Organization Name*', required=True)
180
    org_url = forms.URLField(label='Organization Url*', required=True)
181
    partner_type = forms.ChoiceField(
182
        label='Type of organization*',
183
        required=True, choices=partner_choices)
184
    description = forms.CharField(
185
        label='Describe how your organization will help both of us *',
186
        required=True, widget=forms.Textarea)
187
    python_use = forms.CharField(
188
        label='Use of python in your organization ? *',
189
        required=True, widget=forms.Textarea)
190
    name = forms.CharField(label='Your Name*', required=True)
191
    email = forms.EmailField(label='Your email*', required=True)
192
    contact_number = forms.CharField(
193
        label='Your contact number', required=True)
194
195
    comments = forms.CharField(
196
        label='Comments*',
197
        required=True, widget=forms.Textarea)
198
199
    captcha = MathCaptchaField()
200
201
    def clean_contact_number(self):
202
        contact_number = self.cleaned_data['contact_number']
203
        error_message = []
204
        if not contact_number.isdigit():
205
            error_message.append(
206
                "Contact Number should only consist digits")
207
        if not len(contact_number) == 10:
208
            error_message.append(
209
                "Contact Number should be of 10 digits")
210
211
        if error_message:
212
            raise ValidationError(error_message)
213
        return contact_number
214