views.py 8.57 KB
Newer Older
Sli's avatar
Sli committed
1
from django.shortcuts import redirect
Sli's avatar
Sli committed
2
3
4
5
from django.views.generic import ListView, DetailView, RedirectView
from django.views.generic.edit import UpdateView, CreateView, DeleteView, FormView
from django.core.urlresolvers import reverse_lazy, reverse
from django.utils.translation import ugettext_lazy as _
6
from django.forms.models import modelform_factory
7
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist, ImproperlyConfigured
8
from django.forms import CheckboxSelectMultiple
Sli's avatar
Sli committed
9
from django.utils import timezone
Sli's avatar
Sli committed
10
from django.conf import settings
11
from django import forms
Sli's avatar
Sli committed
12
13

from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin, CanCreateMixin
14
from django.views.generic.edit import FormMixin
15
from core.views.forms import SelectDateTime
16
from election.models import Election, Role, Candidature, ElectionList
Sli's avatar
Sli committed
17

18
19
from ajax_select.fields import AutoCompleteSelectField

20

21
22
23
24
# Forms


class CandidateForm(forms.Form):
25
26
27
28
29
30
31
32
    """ Form to candidate """
    user = AutoCompleteSelectField('users', label=_('User to candidate'), help_text=None, required=True)
    program = forms.CharField(widget=forms.Textarea)

    def __init__(self, election_id, *args, **kwargs):
        super(CandidateForm, self).__init__(*args, **kwargs)
        self.fields['role'] = forms.ModelChoiceField(Role.objects.filter(election__id=election_id))
        self.fields['election_list'] = forms.ModelChoiceField(ElectionList.objects.filter(election__id=election_id))
33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

class VoteForm(forms.Form):
    def __init__(self, role_id, *args, **kwargs):
        super(VoteForm, self).__init__(*args, **kwargs)
        self.max_choice = Role.objects.get(id=role_id).max_choice
        cand = Candidature.objects.filter(role__id=role_id)
        if self.max_choice > 1:
            self.fields['candidature'] = forms.ModelMultipleChoiceField(cand, required=False,
                                                                        widget=forms.CheckboxSelectMultiple())
        else:
            self.fields['candidature'] = forms.ModelChoiceField(cand, required=False,
                                                                widget=forms.RadioSelect(), empty_label=_("Blank vote"))

    def clean_candidature(self):
        data = self.cleaned_data['candidature']
        if self.max_choice > 1 and len(data) > self.max_choice:
            raise forms.ValidationError(_("You have selected too much candidate"))
        return data

Sli's avatar
Sli committed
53
54
55
56
57
58
59
60
61
# Display elections


class ElectionsListView(CanViewMixin, ListView):
    """
    A list with all responsabilities and their candidates
    """
    model = Election
    template_name = 'election/election_list.jinja'
Sli's avatar
Sli committed
62

Sli's avatar
Sli committed
63
64
65
66
67
68
    def get_queryset(self):
        qs = super(ElectionsListView, self).get_queryset()
        today = timezone.now()
        qs = qs.filter(end_date__gte=today, start_date__lte=today)
        return qs

Sli's avatar
Sli committed
69
70
71
72
73
74
75
76
77

class ElectionDetailView(CanViewMixin, DetailView):
    """
    Details an election responsability by responsability
    """
    model = Election
    template_name = 'election/election_detail.jinja'
    pk_url_kwarg = "election_id"

78
79
80
81
82
83
    def get_context_data(self, **kwargs):
        """ Add additionnal data to the template """
        kwargs = super(ElectionDetailView, self).get_context_data(**kwargs)
        kwargs['candidate_form'] = CandidateForm(self.get_object().id)
        return kwargs

Sli's avatar
Sli committed
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

# Form view

class CandidatureCreateView(CanCreateMixin, FormView):
    """
    View dedicated to a cundidature creation
    """
    form_class = CandidateForm
    template_name = 'core/page_prop.jinja'

    def dispatch(self, request, *arg, **kwargs):
        self.election_id = kwargs['election_id']
        return super(CandidatureCreateView, self).dispatch(request, *arg, **kwargs)

    def get_form_kwargs(self):
        kwargs = super(CandidatureCreateView, self).get_form_kwargs()
        kwargs['election_id'] = self.election_id
        return kwargs

    def create_candidature(self, data):
        cand = Candidature(
                role=data['role'],
                user=data['user'],
                election_list=data['election_list'],
                program=data['program']
            )
        cand.save()

    def form_valid(self, form):
        """
            Verify that the selected user is in candidate group
        """
        data = form.clean()
        res = super(FormView, self).form_valid(form)
        data['election'] = Election.objects.get(id=self.election_id)
        if data['user'].is_root:
            self.create_candidature(data)
            return res
        for grp in data['election'].candidature_groups.all():
            if data['user'].is_in_group(grp):
                self.create_candidature(data)
                return res
        return res

    def get_success_url(self, **kwargs):
        return reverse_lazy('election:detail', kwargs={'election_id': self.election_id})


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
class VoteFormView(CanCreateMixin, FormView):
    """
    Alows users to vote
    """
    form_class = VoteForm
    template_name = 'core/page_prop.jinja'

    def dispatch(self, request, *arg, **kwargs):
        self.election_id = kwargs['election_id']
        return super(VoteFormView, self).dispatch(request, *arg, **kwargs)

    def vote(self, data):
        pass

    def get_form_kwargs(self):
        kwargs = super(VoteFormView, self).get_form_kwargs()
        kwargs['role_id'] = self.election_id
        return kwargs

    def form_valid(self, form):
        """
            Verify that the user is part in a vote group
        """
        data = form.clean()
        res = super(FormView, self).form_valid(form)
        if self.request.user.is_root:
            self.vote(data)
            return res
        for grp in data['role'].election.vote_groups.all():
            if self.request.user.is_in_group(grp):
                self.vote(data)
                return res
        return res

    def get_success_url(self, **kwargs):
        return reverse_lazy('election:detail', kwargs={'election_id': self.election_id})

169
# Create views
170

Sli's avatar
Sli committed
171

172
class ElectionCreateView(CanCreateMixin, CreateView):
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    model = Election
    form_class = modelform_factory(Election,
        fields=['title', 'description', 'start_candidature', 'end_candidature', 'start_date', 'end_date',
                'edit_groups', 'view_groups', 'vote_groups', 'candidature_groups'],
        widgets={
            'edit_groups': CheckboxSelectMultiple,
            'view_groups': CheckboxSelectMultiple,
            'edit_groups': CheckboxSelectMultiple,
            'vote_groups': CheckboxSelectMultiple,
            'candidature_groups': CheckboxSelectMultiple,
            'start_date': SelectDateTime,
            'end_date': SelectDateTime,
            'start_candidature': SelectDateTime,
            'end_candidature': SelectDateTime,
        })
    template_name = 'core/page_prop.jinja'

    def get_success_url(self, **kwargs):
        return reverse_lazy('election:detail', kwargs={'election_id': self.object.id})
192
193


Sli's avatar
Sli committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
class RoleCreateView(CanCreateMixin, CreateView):
    model = Role
    form_class = modelform_factory(Role,
        fields=['title', 'election', 'title', 'description', 'max_choice'])
    template_name = 'core/page_prop.jinja'

    def form_valid(self, form):
        """
            Verify that the user can edit proprely
        """
        obj = form.instance
        res = super(CreateView, self).form_valid
        if self.request.user.is_root:
            return res(form)
        if obj.election:
            for grp in obj.election.edit_groups.all():
                if self.request.user.is_in_group(grp):
                    return res(form)
        raise PermissionDenied

    def get_success_url(self, **kwargs):
        return reverse_lazy('election:detail', kwargs={'election_id': self.object.election.id})


218
219
220
221
222
223
224
225
226
227
228
229
230
class ElectionListCreateView(CanCreateMixin, CreateView):
    model = ElectionList
    form_class = modelform_factory(ElectionList,
        fields=['title', 'election'])
    template_name = 'core/page_prop.jinja'

    def form_valid(self, form):
        """
            Verify that the user can vote on this election
        """
        obj = form.instance
        res = super(CreateView, self).form_valid
        if obj.election:
Sli's avatar
Sli committed
231
232
            if self.request.user.is_root:
                return res(form)
233
234
235
236
237
238
239
240
241
242
            for grp in obj.election.candidature_groups.all():
                if self.request.user.is_in_group(grp):
                    return res(form)
            for grp in obj.election.edit_groups.all():
                if self.request.user.is_in_group(grp):
                    return res(form)
        raise PermissionDenied

    def get_success_url(self, **kwargs):
        return reverse_lazy('election:detail', kwargs={'election_id': self.object.election.id})