d0ef1850c2540a531d50e1d035174582fcc0a5d5
[cascardo/ema.git] / eventos / views.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2008 Lincoln de Sousa <lincoln@minaslivre.org>
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License as
6 # published by the Free Software Foundation; either version 2 of the
7 # License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public
15 # License along with this program; if not, write to the
16 # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 # Boston, MA 02111-1307, USA.
18 from django.conf import settings
19 from django.http import HttpResponseRedirect, HttpResponseForbidden
20 from django.contrib.auth import authenticate, login as login_django, \
21     logout as logout_django
22 from django.contrib.auth.models import User, Group
23 from django.forms import HiddenInput, ModelForm
24 from django.shortcuts import render_to_response, get_object_or_404
25 from django.template import RequestContext, Context, loader
26 from eventos.models import Palestrante, Trabalho, TipoTrabalho, Trilha, Evento
27 from eventos.forms import RegisterSpeaker
28
29 forbidden = \
30     HttpResponseForbidden('<h2>You are not allowed to do this action.<h2>')
31
32 class SpeakerForm(ModelForm):
33     class Meta:
34         model = Palestrante
35         exclude = ('usuario',)
36
37 class TalkForm(ModelForm):
38     class Meta:
39         model = Trabalho
40
41 def login(request):
42     """This is a function that will be used as a front-end to the
43     django's login system. It receives username and password fields
44     from a POST request and tries to login the user.
45
46     If login is successful, user will be redirected to the referer
47     address, otherwise will be redirected to /?login_failed.
48     """
49     username = request.POST['username']
50     password = request.POST['password']
51     user = authenticate(username=username, password=password)
52
53     if user is not None:
54         if user.is_active:
55             login_django(request, user)
56             try:
57                 request.session.delete_test_cookie()
58             except KeyError:
59                 pass
60             return HttpResponseRedirect('/')
61         else:
62             return HttpResponseRedirect('/?login_failed')
63     else:
64         return HttpResponseRedirect('/?login_failed')
65
66     request.session.set_test_cookie()
67     return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
68
69 def logout(request):
70     """Simple front-end to django's logout stuff. This function should
71     be mapped to an url and simply called without any parameter.
72     """
73     logout_django(request)
74     return HttpResponseRedirect('/')
75
76 def speaker_add(request):
77     """Adds a new speaker to the system.
78     """
79     uform = RegisterSpeaker(request.POST or None)
80
81     form = SpeakerForm(request.POST or None)
82
83     if request.POST and form.is_valid() and uform.is_valid():
84         cd = uform.cleaned_data
85         group = Group.objects.get_or_create(name='palestrantes')[0]
86
87         # creating the user that will be set as the user of the
88         # speaker.
89         user = User(username=cd['username'])
90         user.set_password(cd['password1'])
91         user.is_active = True
92         user.save()
93         user.groups.add(group)
94
95         # this commit=False is to avoid IntegritErrors, because at
96         # this point, the speaker doesn't have an user associated
97         # with it.
98         instance = form.save(commit=False)
99         instance.usuario = user
100         instance.save()
101         return HttpResponseRedirect('/')
102
103     c = {'form': form, 'uform': uform}
104     return render_to_response('eventos/speaker-add.html', Context(c),
105                               context_instance=RequestContext(request))
106
107 def speaker_details(request, lid):
108     """Shows a simple form containing all editable fields of a
109     speaker and gives the speaker the possibility to save them =)
110     """
111     if not hasattr(request.user, 'palestrante_set'):
112         return forbidden
113
114     entity = request.user.palestrante_set.get()
115     if entity.id != int(lid):
116         return forbidden
117
118     form = SpeakerForm(request.POST or None, instance=entity)
119
120     if request.POST and form.is_valid():
121         form.save()
122
123     c = {'form': form}
124     return render_to_response('eventos/speaker-details.html', Context(c),
125                               context_instance=RequestContext(request))
126
127 def speaker_talks(request, lid):
128     """Lists all talks of a speaker (based on speaker id -- lid
129     parameter).
130     """
131     if not hasattr(request.user, 'palestrante_set'):
132         return forbidden
133
134     entity = request.user.palestrante_set.get()
135     if entity.id != int(lid):
136         return forbidden
137
138     talks = Trabalho.objects.filter(palestrante=entity)
139     c = {'speaker': entity, 'talks': talks}
140     return render_to_response('eventos/talk-list.html', Context(c),
141                               context_instance=RequestContext(request))
142
143 def talk_details(request, tid):
144     """Shows a form to edit a talk
145     """
146     # Selected in settings.py (SITE_ID) variable, because an event can
147     # be linked with only one site.
148     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
149
150     # building the form
151     entity = get_object_or_404(Trabalho, pk=tid)
152     form = TalkForm(request.POST or None, instance=entity)
153
154     # These fields should not be shown to the user.
155     form.fields['palestrante'].widget = HiddenInput()
156     form.fields['evento'].widget = HiddenInput()
157
158     # These fields are event specific
159     trilhas = Trilha.objects.filter(evento=event)
160     form.fields['trilha']._set_queryset(trilhas)
161
162     tipos = TipoTrabalho.objects.filter(evento=event)
163     form.fields['tipo']._set_queryset(tipos)
164
165     # hidding the owner in the other speakers list
166     other = Palestrante.objects.exclude(pk=entity.id)
167     form.fields['outros_palestrantes']._set_queryset(other)
168     if other.count() == 0:
169         # I need set the value to '', otherwise the wise django
170         # newforms will fill the field with the invalid string '[]'
171         form.fields['outros_palestrantes'].initial = ''
172         form.fields['outros_palestrantes'].widget = HiddenInput()
173
174     if request.POST and form.is_valid():
175         form.save()
176
177     c = {'form': form}
178     return render_to_response('eventos/talk-details.html', Context(c),
179                               context_instance=RequestContext(request))
180
181 def talk_delete(request, tid):
182     """Drops a talk but only if the logged in user is its owner.
183     """
184     if not hasattr(request.user, 'palestrante_set'):
185         return forbidden
186
187     entity = request.user.palestrante_set.get()
188     talk = Trabalho.objects.filter(pk=tid, palestrante=entity)
189     if not talk:
190         return forbidden
191
192     talk.delete()
193     return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
194
195 def talk_add(request):
196     """Shows a form to the speaker send a talk
197     """
198     if not hasattr(request.user, 'palestrante_set'):
199         return forbidden
200
201     # building the form
202     form = TalkForm(request.POST or None)
203
204     # These fields should not be shown to the user.
205
206     # Selected in settings.py (SITE_ID) variable, because an event can
207     # be linked with only one site.
208     entity = request.user.palestrante_set.get()
209     form.fields['palestrante'].widget = HiddenInput(attrs={'value' : entity.id})
210
211     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
212     form.fields['evento'].widget = HiddenInput(attrs={'value' : event.id})
213
214     # These fields are event specific
215     trilhas = Trilha.objects.filter(evento=event)
216     form.fields['trilha']._set_queryset(trilhas)
217
218     tipos = TipoTrabalho.objects.filter(evento=event)
219     form.fields['tipo']._set_queryset(tipos)
220
221     # hidding the owner in the other speakers list
222     other = Palestrante.objects.exclude(pk=entity.id)
223     form.fields['outros_palestrantes']._set_queryset(other)
224     if other.count() == 0:
225         form.fields['outros_palestrantes'].widget = HiddenInput()
226
227     if request.POST and form.is_valid():
228         # validation
229         cleaned = form.cleaned_data
230         if cleaned['tipo'].evento.id != event.id:
231             return forbidden
232
233         if cleaned['trilha'].evento.id != event.id:
234             return forbidden
235
236         instance = form.save()
237         return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
238
239     c = {'form': form}
240     return render_to_response('eventos/talk-add.html', Context(c),
241                               context_instance=RequestContext(request))