Replacing the word lecturer by speaker (suggested by cascardo)
[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.http import HttpResponseRedirect, HttpResponseForbidden
19 from django.contrib import auth
20 from django.contrib.auth.forms import AuthenticationForm
21 from django.contrib.auth.models import User, Group
22 from django.newforms import form_for_instance, form_for_model, HiddenInput
23 from django.shortcuts import render_to_response, get_object_or_404
24 from django.template import RequestContext, Context, loader
25 from eventos.models import Palestrante, Trabalho
26 from eventos.forms import RegisterSpeaker
27
28 forbidden = \
29     HttpResponseForbidden('<h2>You are not allowed to do this action.<h2>')
30
31 def login(request):
32     """This is a function that will be used as a front-end to the
33     django's login system. It receives username and password fields
34     from a POST request and tries to login the user.
35
36     If login is successful, user will be redirected to the referer
37     address, otherwise will be redirected to /?login_failed.
38     """
39     errors = {}
40     manipulator = AuthenticationForm(request)
41     if request.POST:
42         errors = manipulator.get_validation_errors(request.POST)
43         got_user = manipulator.get_user()
44         if got_user:
45             auth.login(request, got_user)
46             try:
47                 request.session.delete_test_cookie()
48             except KeyError:
49                 pass
50             return HttpResponseRedirect('/')
51         else:
52             return HttpResponseRedirect('/?login_failed')
53
54     request.session.set_test_cookie()
55     return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
56
57 def logout(request):
58     """Simple front-end to django's logout stuff. This function should
59     be mapped to an url and simply called without any parameter.
60     """
61     auth.logout(request)
62     return HttpResponseRedirect('/')
63
64 def speaker_add(request):
65     """Adds a new speaker to the system.
66     """
67     uform = RegisterSpeaker(request.POST or None)
68
69     FormKlass = form_for_model(Palestrante)
70     form = FormKlass(request.POST or None)
71     del form.fields['usuario']
72
73     if request.POST and form.is_valid() and uform.is_valid():
74         cd = uform.cleaned_data
75         group = Group.objects.get_or_create(name='palestrantes')[0]
76
77         # creating the user that will be set as the user of the
78         # speaker.
79         user = User(username=cd['username'])
80         user.set_password(cd['password1'])
81         user.is_active = True
82         user.save()
83         user.groups.add(group)
84
85         # this commit=False is to avoid IntegritErrors, because at
86         # this point, the speaker doesn't have an user associated
87         # with it.
88         instance = form.save(commit=False)
89         instance.usuario = user
90         instance.save()
91         return HttpResponseRedirect('/')
92
93     c = {'form': form, 'uform': uform}
94     return render_to_response('eventos/speaker-add.html', Context(c),
95                               context_instance=RequestContext(request))
96
97 def speaker_details(request, lid):
98     """Shows a simple form containing all editable fields of a
99     speaker and gives the speaker the possibility to save them =)
100     """
101     if not hasattr(request.user, 'palestrante_set'):
102         return forbidden
103
104     entity = request.user.palestrante_set.get()
105     if entity.id != int(lid):
106         return forbidden
107
108     FormKlass = form_for_instance(entity)
109     del FormKlass.base_fields['usuario']
110
111     form = FormKlass(request.POST or None)
112     if request.POST and form.is_valid():
113         form.save()
114
115     c = {'form': form}
116     return render_to_response('eventos/speaker-details.html', Context(c),
117                               context_instance=RequestContext(request))
118
119 def speaker_talks(request, lid):
120     """Lists all talks of a speaker (based on speaker id -- lid
121     parameter).
122     """
123     if not hasattr(request.user, 'palestrante_set'):
124         return forbidden
125
126     entity = request.user.palestrante_set.get()
127     if entity.id != int(lid):
128         return forbidden
129
130     talks = Trabalho.objects.filter(palestrante=entity)
131     c = {'speaker': entity, 'talks': talks}
132     return render_to_response('eventos/talk-list.html', Context(c),
133                               context_instance=RequestContext(request))
134
135 def talk_details(request, tid):
136     """Shows a form to edit a talk
137     """
138     entity = get_object_or_404(Trabalho, pk=tid)
139     FormKlass = form_for_instance(entity)
140     form = FormKlass(request.POST or None)
141     if request.POST and form.is_valid():
142         form.save()
143
144     c = {'form': form}
145     return render_to_response('eventos/talk-details.html', Context(c),
146                               context_instance=RequestContext(request))
147
148 def talk_delete(request, tid):
149     """Drops a talk but only if the logged in user is its owner.
150     """
151     if not hasattr(request.user, 'palestrante_set'):
152         return forbidden
153
154     entity = request.user.palestrante_set.get()
155     talk = Trabalho.objects.filter(pk=tid, palestrante=entity)
156     if not talk:
157         return forbidden
158
159     talk.delete()
160     return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
161
162 def talk_add(request):
163     """Shows a form to the speaker send a talk
164     """
165     if not hasattr(request.user, 'palestrante_set'):
166         return forbidden
167
168     entity = request.user.palestrante_set.get()
169     FormKlass = form_for_model(Trabalho)
170     form = FormKlass(request.POST or None,
171                      initial={'palestrante': entity.id})
172
173     # This field should not be shown to the user.
174     form.fields['palestrante'].widget = HiddenInput()
175
176     # hidding the owner in the other speakers list
177     other = Palestrante.objects.exclude(pk=entity.id)
178     form.fields['outros_palestrantes']._set_queryset(other)
179
180     if request.POST and form.is_valid():
181         instance = form.save()
182         return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
183
184     c = {'form': form}
185     return render_to_response('eventos/talk-add.html', Context(c),
186                               context_instance=RequestContext(request))