views.py 12.2 KB
Newer Older
chris's avatar
chris committed
1
# Here are the views for sondage
christophe siraut's avatar
christophe siraut committed
2
3
4
5
6
7
8
9

import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import  get_object_or_404, render_to_response
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.forms.formsets import formset_factory
from django.forms.models import inlineformset_factory, BaseInlineFormSet
chris's avatar
chris committed
10
11
from sondage.models import Poll, Choice, Vote, Bulletin
from sondage.forms import PollForm, ChoiceForm, VoteForm, BulletinForm
christophe siraut's avatar
christophe siraut committed
12
13
from django.views.generic.create_update import update_object
from django.contrib.auth.decorators import login_required
14
15
#from django.contrib.sites.models import Site
from django.conf import settings
christophe siraut's avatar
christophe siraut committed
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

def new(request):

    if request.method == 'POST': # If the form has been submitted...

        instance = Poll(author=str(request.user))
        form = PollForm(request.POST, instance=instance) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass

            poll_id = form.cleaned_data.get('title') # Process the data in form.cleaned_data
            new_poll = form.save()

            #if not request.user.is_authenticated(): # Anonymous wants to create a poll...
            key = 'is_' + new_poll.id + '_author'
            request.session[key] = True # This writes cookie

            redir = '/' + str(new_poll.id) + '/edit/choices/'
            return HttpResponseRedirect(redir)

    else:
        form = PollForm() # An unbound form

    return render_to_response('sondage/poll_form.html', {'form': form}, context_instance=RequestContext(request))


@login_required
def secure_update_object(*args, **kwargs):
    """
    Souldn't we provide a better object to the generic view: object_id=poll
    and then simple the template
    # joe = str(request.user)
    # if Poll.objects.get(id=object_id, author=joe):
    """
    return update_object(*args, **kwargs)


def get_ordereditem_formset(form, formset=BaseInlineFormSet, **kwargs):
    return inlineformset_factory(Poll, Choice, form, formset, **kwargs)

def editchoices(request, poll_id):

    poll = get_object_or_404(Poll.objects.all(),id=poll_id)
christophe siraut's avatar
christophe siraut committed
58
    language_code = request.LANGUAGE_CODE
59
    error_message = ''
christophe siraut's avatar
christophe siraut committed
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
    if poll.author == 'AnonymousUser': # Anonymous wants to edit his new poll
        key = 'is_' + poll_id + '_author'
        if not request.session.get(key, False):
            return HttpResponse('')
    else:
        if request.user.is_anonymous():
            return HttpResponse('')
        if request.user.username != poll.author:
            return HttpResponse('')

    OrderedItemFormset = get_ordereditem_formset(ChoiceForm, extra=0, can_delete=True)

    if request.method == "POST":
        """
        Should we set a maximum of choices here?
        #instances = request.POST.values()
        if len(instances) < 20:
            for selection in instances:
        """
        instances = OrderedItemFormset(request.POST, instance=poll)
        if instances.is_valid():
            for instance in instances.cleaned_data:

                try:
                    this_choice = instance['choice']
                    if not instance.get('DELETE'):
                        try:
                            choice = Choice.objects.get(poll=poll,choice=instance['choice'])
                            choice.details = instance['details']
                            choice.save()

                        except (KeyError, Choice.DoesNotExist):
                            choice = Choice(poll=poll, choice=instance['choice'], details=instance['details'])
                            choice.save()
                    else:
                        try:
                            choice = Choice.objects.get(poll=poll,choice=this_choice)
                            """
                            Removing a Choice will remove all childeren Vote objects.
                            When Django deletes an object, it emulates the behavior of
                            the SQL constraint ON DELETE CASCADE -- in other words, any
                            objects which had foreign keys pointing at the object to be
                            deleted will be deleted along with it."""
                            choice.delete()
                        except:
                            pass
                except:
                    pass
            redir = '/' + str(poll.id) + '/'
            return HttpResponseRedirect(redir)
        else:
111
112
113
114
            #vforms=OrderedItemFormset(request.POST, instance=poll)
            error_message = "There are some errors in the form you posted."
            vforms=instances

christophe siraut's avatar
christophe siraut committed
115
    else:
116
117
118
119
120
121
122
123
124
        if Choice.objects.filter(poll=poll_id).count() == 0:
            # Sall we replace next line with something like OrderedItemFormset(extra=2)
            OrderedItemFormset = get_ordereditem_formset(ChoiceForm, extra=2, can_delete=True)
            vforms = OrderedItemFormset()
        else:
            vforms = OrderedItemFormset(instance=poll)

    return render_to_response('sondage/choice_form.html', {'object': poll, 'vforms': vforms, 'error_message' : error_message, 'language_code': language_code,}, context_instance=RequestContext(request))

christophe siraut's avatar
christophe siraut committed
125

126
127
128
129
130
131
132
133
134
135
136
@login_required
def delete(request, poll_id):

    poll = get_object_or_404(Poll.objects.all(),id=poll_id)

    if poll.author == str(request.user):
        poll.delete()

    return HttpResponseRedirect('/')


christophe siraut's avatar
christophe siraut committed
137
138
139
140
141
142
143
144
def make_buletin_form(poll, **kwargs):
    return [ [VoteForm(prefix=choice) ] for choice in Choice.objects.filter(poll=poll.id) ]


def vote(request, poll_id):

    error_message = None
    poll = get_object_or_404(Poll.objects.all(),id=poll_id)
145
    has_voted = False
christophe siraut's avatar
christophe siraut committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

    if request.method == 'POST':

        form = BulletinForm(request.POST,initial={'poll': poll.id,})
        vforms = [ [VoteForm(request.POST, prefix=choice) ] for choice in Choice.objects.filter(poll=poll.id) ]

        if form.is_valid():           
            if request.user.is_authenticated():
                voter = str(request.user)
            else:
                voter = form.cleaned_data['voter']
                if request.session.get('name'):
                    voter = request.session.get('name')

            if voter != 'your name':
                """
                try:
                    Bulletin.objects.get(poll=poll.id,voter=voter)
                    error_message = 'A user with the same name has already voted.'
                    return render_to_response('sondage/poll_detail.html', {'object': poll, 'form': form, 'vforms':vforms, 'error_message':error_message}, context_instance=RequestContext(request))
                except:
                    pass
                """

                if not Bulletin.objects.filter(poll=poll.id,voter=voter):
                    bulletin = Bulletin(poll=poll,voter=voter)
                    bulletin.save()
                else:
                    bulletin = Bulletin.objects.get(poll=poll.id,voter=voter)

                for forms in vforms:
                    for vorm in forms:
                        if vorm.is_valid():
                            try:
                                choice = Choice.objects.get(choice=vorm.cleaned_data['choice'],poll=poll)
                            except:
182
                                return HttpResponse(vorm.cleaned_data['choice'])
christophe siraut's avatar
christophe siraut committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197

                            if not Vote.objects.filter(choice=choice,bulletin=bulletin):
                                vorm.cleaned_data['choice'] = choice
                                new = vorm.save(commit=False)
                                new.bulletin = bulletin
                                #new.choice = choice
                                new.save()
                                if new.voice:
                                    choice.votecount += 1
                                    choice.save()
                                error_message = "Your vote has been counted, thank you."
                                if request.user.is_anonymous(): # Anonymous has voted...
                                    key = 'has_voted-' + poll.id
                                    request.session[key] = True # This writes cookie
                                    request.session['name'] = voter # This writes cookie
198
                                    has_voted = True  # Used to show "Forget me"
christophe siraut's avatar
christophe siraut committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
                            else:
                                old = Vote.objects.get(choice=choice,bulletin=bulletin)

                                if old.voice:
                                    if not vorm.cleaned_data['voice']:
                                        choice.votecount -= 1
                                        choice.save()
                                else:
                                    if vorm.cleaned_data['voice']:
                                        choice.votecount += 1
                                        choice.save()

                                old.voice = vorm.cleaned_data['voice']
                                old.comment = vorm.cleaned_data['comment']
                                old.save()
                                error_message = "Your vote has been updated, thank you."
            else:
                error_message = 'Did you forget to provide your name?'
        else:
            #error_message = form.errors
            error_message = 'Did you forget to provide your name?'
            voter = 'your name'

    else: # request.method = 'GET'

        key = 'is_' + poll.id + '_author'
        if request.session.get(key, False):
            # Assume author is positive for all choices, when he votes for the first time.
            vforms = [ [ VoteForm(initial={'choice': choice,'voice': True,}, prefix=choice) ] for choice in Choice.objects.filter(poll=poll_id) ]
        else:
            # Default formset for unknown user
            vforms = [ [ VoteForm(initial={'choice': choice,}, prefix=choice) ] for choice in Choice.objects.filter(poll=poll_id) ]

        if request.user.is_authenticated():
            voter = str(request.user)
            try:
                bulletin = Bulletin.objects.get(poll=poll,voter=voter)
236
                error_message = " You have voted."
christophe siraut's avatar
christophe siraut committed
237
238
239
240
241
242
243
244
245
246
247
248
                diff = len(vforms) - len(Vote.objects.filter(bulletin=bulletin))
                if diff == 0:
                    """
                    Hum, previously bulletin has not the same amount of vote objects,
                    we should concatenate the existing votes with empty remaing ones...
                    Give an empty bulletin for now.
                    """
                    vforms = [ [ VoteForm(initial={'choice': vote.choice,'voice': vote.voice, 'comment': vote.comment,}, prefix=vote.choice) ] for vote in Vote.objects.filter(bulletin=bulletin) ]

            except:
                pass
        else:
249
            voter = ''
christophe siraut's avatar
christophe siraut committed
250
251
252
            error_message = "Login let you modify your vote anytime."
            key = 'has_voted-' + poll.id
            if request.session.get(key, False):
253
                has_voted = True  # Used to show "Forget me"
christophe siraut's avatar
christophe siraut committed
254
255
256
257
                voter = request.session.get('name')
                #error_message = 'Modify your vote? (clear cookie if you are not ' + voter + ')'
                try:
                    bulletin = Bulletin.objects.get(poll=poll,voter=voter)
258
                    error_message = voter + ' has voted'
christophe siraut's avatar
christophe siraut committed
259
260
261
262
263
264
265
266
267
268
269
270
                    diff = len(vforms) - len(Vote.objects.filter(bulletin=bulletin))
                    if diff == 0:
                        """
                        Hum, previously bulletin has not the same amount of vote objects,
                        we should concatenate the existing votes with empty remaing ones...
                        Give an empty bulletin for now.
                        """
                        vforms = [ [ VoteForm(initial={'choice': vote.choice,'voice': vote.voice, 'comment': vote.comment,}, prefix=vote.choice) ] for vote in Vote.objects.filter(bulletin=bulletin) ]

                except:
                    pass

271
272
    form = BulletinForm(instance=poll,initial={'voter': voter})
    #form = BulletinForm(instance=poll)
273
    current_site = settings.SITE + poll.id
274
    return render_to_response('sondage/poll_detail.html', {'object': poll, 'form': form, 'vforms':vforms, 'error_message':error_message, 'has_voted': has_voted, 'current_site': current_site}, context_instance=RequestContext(request))
christophe siraut's avatar
christophe siraut committed
275
276