1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2008 Lincoln de Sousa <lincoln@minaslivre.org>
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.
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.
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 import forms
25 from django.shortcuts import render_to_response, get_object_or_404
26 from django.template import RequestContext, Context, loader
27 from eventos.models import Palestrante, Trabalho, TipoTrabalho, Trilha, Evento, Improve
28 from eventos.forms import RegisterSpeaker
29 from django.db.models import Q
32 HttpResponseForbidden('<h2>You are not allowed to do this action.<h2>')
34 class SpeakerForm(ModelForm):
37 exclude = ('usuario',)
39 class TalkForm(ModelForm):
43 class ImproveForm(ModelForm):
47 class SubscribeForm(forms.Form):
48 full_name = forms.CharField(label=u'Nome completo', max_length=255)
49 email = forms.EmailField()
50 username = forms.CharField(max_length=255)
51 password = forms.CharField(label=u'Senha',
53 widget=forms.PasswordInput)
54 confirm_password = forms.CharField(label=u'Confirmar senha',
56 widget=forms.PasswordInput)
58 def clean_username(self):
59 data = self.cleaned_data['username']
60 if User.objects.filter(username=data):
61 raise forms.ValidationError(u'O usuário "%s" já existe' % data)
64 def clean_confirm_password(self):
65 passwd = self.cleaned_data['password']
66 conf_passwd = self.cleaned_data['confirm_password']
67 if passwd != conf_passwd:
68 raise forms.ValidationError(u'A confirmação difere da senha')
72 """This is a function that will be used as a front-end to the
73 django's login system. It receives username and password fields
74 from a POST request and tries to login the user.
76 If login is successful, user will be redirected to the referer
77 address, otherwise will be redirected to /?login_failed.
79 username = request.POST['username']
80 password = request.POST['password']
82 user = authenticate(username=username, password=password)
86 login_django(request, user)
88 request.session.delete_test_cookie()
91 return HttpResponseRedirect('/')
93 return HttpResponseRedirect('/?login_failed')
95 return HttpResponseRedirect('/?login_failed')
97 request.session.set_test_cookie()
98 return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
101 """Simple front-end to django's logout stuff. This function should
102 be mapped to an url and simply called without any parameter.
104 logout_django(request)
105 return HttpResponseRedirect('/')
107 def speaker_add(request):
108 """Adds a new speaker to the system.
110 uform = RegisterSpeaker(request.POST or None)
112 form = SpeakerForm(request.POST or None)
114 if request.POST and form.is_valid() and uform.is_valid():
115 cd = uform.cleaned_data
116 group = Group.objects.get_or_create(name='palestrantes')[0]
118 # creating the user that will be set as the user of the
120 user = User(username=cd['username'])
121 user.set_password(cd['password1'])
122 user.is_active = True
124 user.groups.add(group)
126 # this commit=False is to avoid IntegritErrors, because at
127 # this point, the speaker doesn't have an user associated
129 instance = form.save(commit=False)
130 instance.usuario = user
132 return HttpResponseRedirect('/')
134 c = {'form': form, 'uform': uform}
135 return render_to_response('eventos/speaker-add.html', Context(c),
136 context_instance=RequestContext(request))
138 def speaker_details(request, lid):
139 """Shows a simple form containing all editable fields of a
140 speaker and gives the speaker the possibility to save them =)
142 speaker = get_object_or_404(Palestrante, pk=lid)
143 d = {'speaker' : speaker}
144 if not hasattr(request.user, 'palestrante_set'):
145 return render_to_response('eventos/speaker-details2.html', Context(d),
146 context_instance=RequestContext(request))
148 entity = request.user.palestrante_set.get()
149 if entity.id != int(lid):
150 return render_to_response('eventos/speaker-details2.html', Context(d),
151 context_instance=RequestContext(request))
153 form = SpeakerForm(request.POST or None, instance=entity)
155 if request.POST and form.is_valid():
159 return render_to_response('eventos/speaker-details.html', Context(c),
160 context_instance=RequestContext(request))
162 def speaker_talks(request, lid):
163 """Lists all talks of a speaker (based on speaker id -- lid
166 if not hasattr(request.user, 'palestrante_set'):
169 entity = request.user.palestrante_set.get()
170 if entity.id != int(lid):
173 talks = Trabalho.objects.filter(
174 Q(palestrante=entity) | Q(outros_palestrantes=entity) )
176 c = {'speaker': entity, 'talks': talks}
177 return render_to_response('eventos/talk-list.html', Context(c),
178 context_instance=RequestContext(request))
180 def talk_details(request, tid):
181 """Shows a form to edit a talk
183 # If the user is not a speaker we should not try to show anything.
184 if not hasattr(request.user, 'palestrante_set'):
187 # Selected in settings.py (SITE_ID) variable, because an event can
188 # be linked with only one site.
189 event = Evento.objects.get(site__id__exact=settings.SITE_ID)
192 entity = get_object_or_404(Trabalho, pk=tid)
193 form = TalkForm(request.POST or None, instance=entity)
195 # These fields should not be shown to the user.
196 form.fields['palestrante'].widget = HiddenInput()
197 form.fields['evento'].widget = HiddenInput()
199 # These fields are event specific
200 trilhas = Trilha.objects.filter(evento=event)
201 form.fields['trilha']._set_queryset(trilhas)
203 tipos = TipoTrabalho.objects.filter(evento=event)
204 form.fields['tipo']._set_queryset(tipos)
206 # hidding the owner in the other speakers list
207 other = Palestrante.objects.exclude(pk=entity.id)
208 form.fields['outros_palestrantes']._set_queryset(other)
209 if other.count() == 0:
210 # I need set the value to '', otherwise the wise django
211 # newforms will fill the field with the invalid string '[]'
212 form.fields['outros_palestrantes'].initial = ''
213 form.fields['outros_palestrantes'].widget = HiddenInput()
215 # avoiding smart people trying to se talks of other speakers.
216 speaker = request.user.palestrante_set.get()
217 if speaker.id != entity.palestrante.id \
218 and speaker not in entity.outros_palestrantes.all():
221 if request.POST and form.is_valid():
225 return render_to_response('eventos/talk-details.html', Context(c),
226 context_instance=RequestContext(request))
228 def talk_delete(request, tid):
229 """Drops a talk but only if the logged in user is its owner.
231 if not hasattr(request.user, 'palestrante_set'):
234 entity = request.user.palestrante_set.get()
235 talk = Trabalho.objects.filter(pk=tid, palestrante=entity)
240 return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
242 def talk_add(request):
243 """Shows a form to the speaker send a talk
245 if not hasattr(request.user, 'palestrante_set'):
249 form = TalkForm(request.POST or None)
251 # These fields should not be shown to the user.
253 # Selected in settings.py (SITE_ID) variable, because an event can
254 # be linked with only one site.
255 entity = request.user.palestrante_set.get()
256 form.fields['palestrante'].widget = HiddenInput(attrs={'value' : entity.id})
258 event = Evento.objects.get(site__id__exact=settings.SITE_ID)
259 form.fields['evento'].widget = HiddenInput(attrs={'value' : event.id})
261 # These fields are event specific
262 trilhas = Trilha.objects.filter(evento=event)
263 form.fields['trilha']._set_queryset(trilhas)
265 tipos = TipoTrabalho.objects.filter(evento=event)
266 form.fields['tipo']._set_queryset(tipos)
268 # hidding the owner in the other speakers list
269 other = Palestrante.objects.exclude(pk=entity.id)
270 form.fields['outros_palestrantes']._set_queryset(other)
271 if other.count() == 0:
272 form.fields['outros_palestrantes'].widget = HiddenInput()
274 if request.POST and form.is_valid():
276 cleaned = form.cleaned_data
277 if cleaned['tipo'].evento.id != event.id:
280 if cleaned['trilha'].evento.id != event.id:
283 instance = form.save()
284 return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
287 return render_to_response('eventos/talk-add.html', Context(c),
288 context_instance=RequestContext(request))
290 def list_all_talks(request):
291 event = Evento.objects.get(site__id__exact=settings.SITE_ID)
292 trilhas = Trilha.objects.filter(evento=event)
296 talks = Trabalho.objects.filter(trilha=t)
297 aux = {'trilha':t.nome, 'talks':talks}
300 c = {'improve': improve,}
301 return render_to_response('eventos/improve.html', Context(c),
302 context_instance=RequestContext(request))
304 def talk_improve(request, tid):
305 if not hasattr(request.user, 'palestrante_set') and request.POST:
308 talk = get_object_or_404(Trabalho, pk=tid)
309 speaker = talk.palestrante
310 improve = Improve.objects.filter(trabalho=talk)
313 form = ImproveForm(request.POST or None)
314 form.fields['trabalho'].widget = HiddenInput(attrs={'value':talk.id})
315 form.fields['usuario'].widget = HiddenInput(attrs={'value':request.user.id})
317 if request.POST and form.is_valid():
318 event = Evento.objects.get(site__id__exact=settings.SITE_ID)
320 cleaned = form.cleaned_data
321 if cleaned['trabalho'].evento.id != event.id:
324 instance = form.save()
325 return HttpResponseRedirect('/improve/%d/' % talk.id)
327 c = {'talk': talk, 'form': form, 'improve': improve,
328 'len_comments': len(improve), 'speaker': speaker}
329 return render_to_response('eventos/talk-improve.html', Context(c),
330 context_instance=RequestContext(request))
332 def subscribe(request):
333 """This view shows a form with name, login and password fields and
334 if it receives a post, it will get data from the above fields and
335 create an User (yes, the django User). I think this user will be
338 This function authenticates the new user.
340 form = SubscribeForm(request.POST or None)
342 if request.POST and form.is_valid():
343 new_user = User.objects.create_user(request.POST['username'],
344 request.POST['email'],
345 request.POST['password'])
347 return HttpResponseRedirect('/')
349 context = {'form': form}
350 return render_to_response('eventos/subscribe.html', Context(context),
351 context_instance=RequestContext(request))