remoção do usuário autenticado na lista de *outros palestrantes*
[cascardo/eventmanager.git] / views.py
1 # -*- coding: utf-8; -*-
2 """
3 Copyright (C) 2007 Lincoln de Sousa <lincoln@archlinux-br.org>
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public
16 License along with this program; if not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 """
20 from django.shortcuts import render_to_response
21 from django.template import RequestContext, Context
22 from django.contrib.auth.decorators import login_required, user_passes_test
23 from django.contrib.auth.models import Group, User
24 from django.contrib.auth.forms import AuthenticationForm
25 from django.contrib.auth import login
26 from django.db import transaction
27
28 from eventmanager.decorators import enable_login_form
29 from eventmanager.forms import *
30 from eventmanager.conteudo.models import Noticia, Menu, Secao
31 from eventmanager.eventos.models import *
32
33 def build_response(request, template, extra={}):
34     """
35     Shortcut to build a response based on a C{template} and build a standard
36     context to this template. This context contains news itens, a list of menus
37     and a list of sections to be shown on index. But don't worry, this context
38     is extensible through the C{extra} parameter.
39
40     @param template: Contains the name of a template found in django
41      C{TEMPLATE_DIRS}
42     @type template: C{str}
43
44     @param extra: Extra variables to be passed to the context being built.
45     @type extra: C{dict}
46     """
47     news = Noticia.objects.order_by('-data_criacao')
48     menus = Menu.objects.all()
49     index_sections = Secao.objects.filter(index=True)
50     c = {'news': news, 'menu': menus,
51         'index_sections': index_sections}
52     c.update(extra)
53     return render_to_response(template, Context(c),
54             context_instance=RequestContext(request))
55
56
57 @enable_login_form
58 def index(request):
59     return build_response(request, 'index.html')
60
61
62 @transaction.commit_manually
63 @enable_login_form
64 def cadastro_palestrante(request):
65     form = CadastroPalestrante(request.POST or None)
66     ok = False
67     if request.POST and form.is_valid():
68         cd = form.cleaned_data
69         badattr = form.errors
70         wrong = False
71
72         if not cd['telefone'] and not cd['celular']:
73             badattr['telefone_comercial'] = ['Algum número de telefone '
74                                              'precisa ser informado']
75             wrong = True
76
77         # don't save duplicated users...
78         try:
79             User.objects.get(username=cd['nome_usuario'])
80             badattr['nome_usuario'] = ['Este nome de usuário já existe!']
81             wrong = True
82             transaction.rollback()
83         except User.DoesNotExist:
84             pass
85
86         if cd['senha'] != cd['senha_2']:
87             badattr['senha_2'] = ['A senha não confere']
88             wrong = True
89             transaction.rollback()
90
91         if not wrong:
92             group = Group.objects.get_or_create(name='palestrantes')[0]
93
94             user = User(username=cd['nome_usuario'], email=cd['email'])
95             user.set_password(cd['senha'])
96             user.save()
97             user.groups.add(group)
98
99             p = Palestrante()
100             p.usuario = user
101
102             p.nome = cd['nome_completo']
103             p.email = cd['email']
104             p.telefone = cd['telefone']
105             p.celular = cd['celular']
106             p.instituicao = cd['instituicao']
107             p.rua = cd['rua']
108             p.numero = cd['numero']
109             p.bairro = cd['bairro']
110             p.cidade = cd['cidade']
111             p.uf = cd['uf']
112             p.minicurriculo = cd['minicurriculo']
113             p.curriculo = cd['curriculo']
114             p.save()
115
116             for i in cd.get('area_interesse', []):
117                 p.area_interesse.add(i)
118
119             fakepost = request.POST.copy()
120             fakepost['username'] = cd['nome_usuario']
121             fakepost['password'] = cd['senha']
122
123             manipulator = AuthenticationForm(request)
124             errors = manipulator.get_validation_errors(fakepost)
125             got_user = manipulator.get_user()
126             login(request, got_user)
127             transaction.commit()
128             ok = True
129     c = {'form': form, 'ok': ok}
130     return build_response(request, 'cadastro.html', c)
131
132
133 @enable_login_form
134 def inscricao(request):
135     form = Inscricao(request.POST or None)
136     return build_response(request, 'inscricao.html', {'form': form})
137
138
139 @login_required
140 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
141 def submeter_trabalho(request):
142     form = SubmeterTrabalho(request, request.POST or None)
143     ok = False
144
145     if request.POST and form.is_valid():
146         cd = form.cleaned_data
147         t = Trabalho()
148         t.titulo = cd['titulo']
149         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
150         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
151         t.descricao_curta = cd['descricao_curta']
152         t.descricao_longa = cd['descricao_longa']
153         t.recursos = cd['recursos']
154         t.evento = Evento.objects.get(pk=1) # let the hammer play arround!
155         t.save()
156
157         logged_in = request.user.palestrante_set.get()
158         t.palestrante.add(logged_in)
159         for i in cd.get('outros_palestrantes', []):
160             up = Palestrante.objects.get(pk=int(i))
161             t.palestrante.add(up)
162         ok = True
163
164     c = {'form': form, 'ok': ok}
165     return build_response(request, 'inscrever_palestra.html', c)
166
167
168 @login_required
169 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
170 def meus_trabalhos(request):
171     try:
172         p = Palestrante.objects.get(usuario=request.user)
173     except Palestrante.DoesNotExist:
174         # não palestrante...
175         c = {'palestrante': 0}
176         return build_response(request, 'meus_trabalhos.html', c)
177
178     t = Trabalho.objects.filter(palestrante=p)
179     c = {'trabalhos': t, 'palestrante': 1}
180     return build_response(request, 'meus_trabalhos.html', c)
181
182
183 @login_required
184 def meus_dados(request):
185     form = EditarPalestrante(request.POST or None)
186     palestrante = request.user.palestrante_set.get()
187     ok = False
188
189     for name, field in form.fields.items():
190         field.initial = getattr(palestrante, name)
191
192     if request.POST and form.is_valid():
193         cd = form.cleaned_data
194         for name, field in form.fields.items():
195             setattr(palestrante, name, cd[name])
196         palestrante.save()
197         ok = True
198
199     c = {'form': form, 'ok': ok}
200     return build_response(request, 'editar_palestrante.html', c)
201
202
203 @enable_login_form
204 def chamada_trabalhos(request):
205     return build_response(request, 'chamada_trabalhos.html')