adding images to the new layout
[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 import auth
21 from django.contrib.auth.forms import AuthenticationForm
22 from django.contrib.auth.models import User, Group
23 from django.newforms import form_for_instance, form_for_model, HiddenInput
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 def login(request):
33     """This is a function that will be used as a front-end to the
34     django's login system. It receives username and password fields
35     from a POST request and tries to login the user.
36
37     If login is successful, user will be redirected to the referer
38     address, otherwise will be redirected to /?login_failed.
39     """
40     errors = {}
41     manipulator = AuthenticationForm(request)
42     if request.POST:
43         errors = manipulator.get_validation_errors(request.POST)
44         got_user = manipulator.get_user()
45         if got_user:
46             auth.login(request, got_user)
47             try:
48                 request.session.delete_test_cookie()
49             except KeyError:
50                 pass
51             return HttpResponseRedirect('/')
52         else:
53             return HttpResponseRedirect('/?login_failed')
54
55     request.session.set_test_cookie()
56     return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
57
58 def logout(request):
59     """Simple front-end to django's logout stuff. This function should
60     be mapped to an url and simply called without any parameter.
61     """
62     auth.logout(request)
63     return HttpResponseRedirect('/')
64
65 def speaker_add(request):
66     """Adds a new speaker to the system.
67     """
68     uform = RegisterSpeaker(request.POST or None)
69
70     FormKlass = form_for_model(Palestrante)
71     form = FormKlass(request.POST or None)
72     del form.fields['usuario']
73
74     if request.POST and form.is_valid() and uform.is_valid():
75         cd = uform.cleaned_data
76         group = Group.objects.get_or_create(name='palestrantes')[0]
77
78         # creating the user that will be set as the user of the
79         # speaker.
80         user = User(username=cd['username'])
81         user.set_password(cd['password1'])
82         user.is_active = True
83         user.save()
84         user.groups.add(group)
85
86         # this commit=False is to avoid IntegritErrors, because at
87         # this point, the speaker doesn't have an user associated
88         # with it.
89         instance = form.save(commit=False)
90         instance.usuario = user
91         instance.save()
92         return HttpResponseRedirect('/')
93
94     c = {'form': form, 'uform': uform}
95     return render_to_response('eventos/speaker-add.html', Context(c),
96                               context_instance=RequestContext(request))
97
98 def speaker_details(request, lid):
99     """Shows a simple form containing all editable fields of a
100     speaker and gives the speaker the possibility to save them =)
101     """
102     if not hasattr(request.user, 'palestrante_set'):
103         return forbidden
104
105     entity = request.user.palestrante_set.get()
106     if entity.id != int(lid):
107         return forbidden
108
109     FormKlass = form_for_instance(entity)
110     del FormKlass.base_fields['usuario']
111
112     form = FormKlass(request.POST or None)
113     if request.POST and form.is_valid():
114         form.save()
115
116     c = {'form': form}
117     return render_to_response('eventos/speaker-details.html', Context(c),
118                               context_instance=RequestContext(request))
119
120 def speaker_talks(request, lid):
121     """Lists all talks of a speaker (based on speaker id -- lid
122     parameter).
123     """
124     if not hasattr(request.user, 'palestrante_set'):
125         return forbidden
126
127     entity = request.user.palestrante_set.get()
128     if entity.id != int(lid):
129         return forbidden
130
131     talks = Trabalho.objects.filter(palestrante=entity)
132     c = {'speaker': entity, 'talks': talks}
133     return render_to_response('eventos/talk-list.html', Context(c),
134                               context_instance=RequestContext(request))
135
136 def talk_details(request, tid):
137     """Shows a form to edit a talk
138     """
139     # Selected in settings.py (SITE_ID) variable, because an event can
140     # be linked with only one site.
141     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
142
143     # building the form
144     entity = get_object_or_404(Trabalho, pk=tid)
145     FormKlass = form_for_instance(entity)
146     form = FormKlass(request.POST or None)
147
148     # These fields should not be shown to the user.
149     form.fields['palestrante'].widget = HiddenInput()
150     form.fields['evento'].widget = HiddenInput()
151
152     # These fields are event specific
153     trilhas = Trilha.objects.filter(evento=event)
154     form.fields['trilha']._set_queryset(trilhas)
155
156     tipos = TipoTrabalho.objects.filter(evento=event)
157     form.fields['tipo']._set_queryset(tipos)
158
159     # hidding the owner in the other speakers list
160     other = Palestrante.objects.exclude(pk=entity.id)
161     form.fields['outros_palestrantes']._set_queryset(other)
162     if other.count() == 0:
163         # I need set the value to '', otherwise the wise django
164         # newforms will fill the field with the invalid string '[]'
165         form.fields['outros_palestrantes'].initial = ''
166         form.fields['outros_palestrantes'].widget = HiddenInput()
167
168     if request.POST and form.is_valid():
169         form.save()
170
171     c = {'form': form}
172     return render_to_response('eventos/talk-details.html', Context(c),
173                               context_instance=RequestContext(request))
174
175 def talk_delete(request, tid):
176     """Drops a talk but only if the logged in user is its owner.
177     """
178     if not hasattr(request.user, 'palestrante_set'):
179         return forbidden
180
181     entity = request.user.palestrante_set.get()
182     talk = Trabalho.objects.filter(pk=tid, palestrante=entity)
183     if not talk:
184         return forbidden
185
186     talk.delete()
187     return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
188
189 def talk_add(request):
190     """Shows a form to the speaker send a talk
191     """
192     if not hasattr(request.user, 'palestrante_set'):
193         return forbidden
194
195     # Selected in settings.py (SITE_ID) variable, because an event can
196     # be linked with only one site.
197     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
198
199     # building the form
200     entity = request.user.palestrante_set.get()
201     FormKlass = form_for_model(Trabalho)
202     form = FormKlass(request.POST or None,
203                      initial={'palestrante': entity.id, 'evento': event.id})
204
205     # These fields should not be shown to the user.
206     form.fields['palestrante'].widget = HiddenInput()
207     form.fields['evento'].widget = HiddenInput()
208
209     # These fields are event specific
210     trilhas = Trilha.objects.filter(evento=event)
211     form.fields['trilha']._set_queryset(trilhas)
212
213     tipos = TipoTrabalho.objects.filter(evento=event)
214     form.fields['tipo']._set_queryset(tipos)
215
216     # hidding the owner in the other speakers list
217     other = Palestrante.objects.exclude(pk=entity.id)
218     form.fields['outros_palestrantes']._set_queryset(other)
219     if other.count() == 0:
220         form.fields['outros_palestrantes'].widget = HiddenInput()
221
222     if request.POST and form.is_valid():
223         # validation
224         cleaned = form.cleaned_data
225         if cleaned['tipo'].evento.id != event.id:
226             return forbidden
227
228         if cleaned['trilha'].evento.id != event.id:
229             return forbidden
230
231         instance = form.save()
232         return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
233
234     c = {'form': form}
235     return render_to_response('eventos/talk-add.html', Context(c),
236                               context_instance=RequestContext(request))