EN:
[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, get_object_or_404
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 from django.newforms import form_for_instance
33
34 def build_response(request, template, extra={}):
35     """
36     Shortcut to build a response based on a C{template} and build a standard
37     context to this template. This context contains news itens, a list of menus
38     and a list of sections to be shown on index. But don't worry, this context
39     is extensible through the C{extra} parameter.
40
41     @param template: Contains the name of a template found in django
42      C{TEMPLATE_DIRS}
43     @type template: C{str}
44
45     @param extra: Extra variables to be passed to the context being built.
46     @type extra: C{dict}
47     """
48     news = Noticia.objects.order_by('-data_criacao')
49     menus = Menu.objects.all()
50     index_sections = Secao.objects.filter(index=True)
51     c = {'news': news, 'menu': menus,
52         'index_sections': index_sections}
53     c.update(extra)
54     return render_to_response(template, Context(c),
55             context_instance=RequestContext(request))
56
57
58 @enable_login_form
59 def index(request):
60     return build_response(request, 'index.html')
61
62
63 @transaction.commit_manually
64 @enable_login_form
65 def cadastro_palestrante(request):
66     form = CadastroPalestrante(request.POST or None)
67     ok = False
68     if request.POST and form.is_valid():
69         cd = form.cleaned_data
70         badattr = form.errors
71         wrong = False
72
73         if not cd['telefone'] and not cd['celular']:
74             badattr['telefone_comercial'] = ['Algum número de telefone '
75                                              'precisa ser informado']
76             wrong = True
77
78         # don't save duplicated users...
79         try:
80             User.objects.get(username=cd['nome_usuario'])
81             badattr['nome_usuario'] = ['Este nome de usuário já existe!']
82             wrong = True
83             transaction.rollback()
84         except User.DoesNotExist:
85             pass
86
87         if cd['senha'] != cd['senha_2']:
88             badattr['senha_2'] = ['A senha não confere']
89             wrong = True
90             transaction.rollback()
91
92         if not wrong:
93             group = Group.objects.get_or_create(name='palestrantes')[0]
94
95             user = User(username=cd['nome_usuario'], email=cd['email'])
96             user.set_password(cd['senha'])
97             user.save()
98             user.groups.add(group)
99
100             p = Palestrante()
101             p.usuario = user
102
103             p.nome = cd['nome_completo']
104             p.email = cd['email']
105             p.telefone = cd['telefone']
106             p.celular = cd['celular']
107             p.instituicao = cd['instituicao']
108             p.rua = cd['rua']
109             p.numero = cd['numero']
110             p.bairro = cd['bairro']
111             p.cidade = cd['cidade']
112             p.uf = cd['uf']
113             p.minicurriculo = cd['minicurriculo']
114             p.curriculo = cd['curriculo']
115             p.save()
116
117             for i in cd.get('area_interesse', []):
118                 p.area_interesse.add(i)
119
120             fakepost = request.POST.copy()
121             fakepost['username'] = cd['nome_usuario']
122             fakepost['password'] = cd['senha']
123
124             manipulator = AuthenticationForm(request)
125             errors = manipulator.get_validation_errors(fakepost)
126             got_user = manipulator.get_user()
127             login(request, got_user)
128             transaction.commit()
129             ok = True
130     c = {'form': form, 'ok': ok}
131     return build_response(request, 'cadastro.html', c)
132
133
134 @enable_login_form
135 def inscricao(request):
136     form = Inscricao(request.POST or None)
137     return build_response(request, 'inscricao.html', {'form': form})
138
139
140 @login_required
141 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
142 def submeter_trabalho(request):
143     form = SubmeterTrabalho(request, request.POST or None)
144     ok = False
145
146     if request.POST and form.is_valid():
147         cd = form.cleaned_data
148         t = Trabalho()
149         t.titulo = cd['titulo']
150         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
151         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
152         t.descricao_curta = cd['descricao_curta']
153         t.descricao_longa = cd['descricao_longa']
154         t.recursos = cd['recursos']
155         t.evento = Evento.objects.get(pk=1) # let the hammer play arround!
156         t.save()
157
158         logged_in = request.user.palestrante_set.get()
159         t.palestrante.add(logged_in)
160         for i in cd.get('outros_palestrantes', []):
161             up = Palestrante.objects.get(pk=int(i))
162             t.palestrante.add(up)
163         ok = True
164
165     c = {'form': form, 'ok': ok}
166     return build_response(request, 'inscrever_palestra.html', c)
167
168
169 @login_required
170 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
171 def meus_trabalhos(request):
172     try:
173         p = Palestrante.objects.get(usuario=request.user)
174     except Palestrante.DoesNotExist:
175         # não palestrante...
176         c = {'palestrante': 0}
177         return build_response(request, 'meus_trabalhos.html', c)
178     t = Trabalho.objects.filter(palestrante=p)
179     c = {'trabalhos': t, 'palestrante': 1}
180     return build_response(request, 'meus_trabalhos.html', c)
181
182 @login_required
183 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
184 def editar_trabalho(request,codigo):
185     try:
186         p = Palestrante.objects.get(usuario=request.user)
187     except Palestrante.DoesNotExist:
188         # não palestrante...
189         c = {'palestrante': 0}
190         return build_response(request, 'meus_trabalhos.html', c)
191     trabalho = get_object_or_404(Trabalho, id=codigo,palestrante=p)
192     Formulario = form_for_instance(trabalho)
193     if request.method == 'POST':
194         form = Formulario(request.POST)
195         if form.is_valid():
196             form.save()
197             t = Trabalho.objects.filter(palestrante=p)
198             c = {'trabalhos': t, 'palestrante': 1}
199             c['editado_sucesso']=trabalho.titulo
200             return build_response(request, 'meus_trabalhos.html', c)
201     else:
202         form = Formulario()
203     
204     c = {'formulario':form}
205     return build_response(request, 'editar_trabalho.html', c)
206
207 @login_required
208 def meus_dados(request):
209     form = EditarPalestrante(request.POST or None)
210     palestrante = request.user.palestrante_set.get()
211     ok = False
212
213     for name, field in form.fields.items():
214         field.initial = getattr(palestrante, name)
215
216     if request.POST and form.is_valid():
217         cd = form.cleaned_data
218         for name, field in form.fields.items():
219             setattr(palestrante, name, cd[name])
220         palestrante.save()
221         ok = True
222
223     c = {'form': form, 'ok': ok}
224     return build_response(request, 'editar_palestrante.html', c)
225
226
227 @enable_login_form
228 def chamada_trabalhos(request):
229     return build_response(request, 'chamada_trabalhos.html')
230
231 @enable_login_form
232 def avaliacao(request):
233     return build_response(request, 'avaliacao.html')