RegionalLeadForm.clean()   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
c 0
b 0
f 0
dl 0
loc 13
rs 7.3333
1
from django import forms
2
from django.core.exceptions import ValidationError
3
4
from wye.profiles.models import UserType, Profile
5
6
from . import models
7
8
9
class RegionalLeadForm(forms.ModelForm):
10
11
    class Meta:
12
        model = models.RegionalLead
13
        exclude = ()
14
15
    def clean(self):
16
        error_message = []
17
        if (self.cleaned_data.get('location', '') and
18
                self.cleaned_data.get('leads', '')):
19
            location = self.cleaned_data['location']
20
            for u in self.cleaned_data['leads']:
21
                if not u.profile:
22
                    error_message.append('Profile for user %s not found' % (u))
23
                elif u.profile.location != location:
24
                    error_message.append(
25
                        "User %s doesn't belong to region %s" % (u, location))
26
        if error_message:
27
            raise ValidationError(error_message)
28
29
    def save(self, force_insert=False, force_update=False, commit=True):
30
        m = super(RegionalLeadForm, self).save()
31
32
        # Removing old leads which are not selected currently
33
        current_region = self.instance.location.id
34
        lead_users = Profile.objects.filter(
35
            usertype=UserType.objects.get(slug='lead'),
36
            location=current_region)
37
        current_leads = self.instance.leads.values_list('id', flat=True)
38
        for lead in lead_users:
39
            if lead.user_id not in current_leads:
40
                lead.usertype.remove(UserType.objects.get(slug='lead'))
41
                lead.save()
42
43
        # Add currently selected leads
44
        for u in self.cleaned_data['leads']:
45
            u.profile.usertype.add(UserType.objects.get(slug='lead'))
46
        return m
47
48
49
class LocationForm(forms.ModelForm):
50
51
    class Meta:
52
        model = models.Location
53
        exclude = ()
54
55
56
class StateForm(forms.ModelForm):
57
58
    class Meta:
59
        model = models.State
60
        exclude = ()
61