adicionando patch do gabriel (brigaduxo =) e arrumando um probleminha no form de...
[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, loader
22 from django.contrib.auth.decorators import login_required, user_passes_test
23 from django.contrib.auth.models import Group, User
24 from django.newforms import form_for_instance
25 from django.core.mail import EmailMessage
26 from django.db import transaction
27 from django.http import get_host
28
29 from eventmanager.decorators import enable_login_form
30 from eventmanager.forms import *
31 from eventmanager.conteudo.models import Noticia, Menu, Secao
32 from eventmanager.eventos.models import *
33 import sha
34
35 FROM_EMAIL = 'Emsl 2007 <noreply@minaslivre.org>'
36
37 def build_response(request, template, extra={}):
38     """
39     Shortcut to build a response based on a C{template} and build a standard
40     context to this template. This context contains news itens, a list of menus
41     and a list of sections to be shown on index. But don't worry, this context
42     is extensible through the C{extra} parameter.
43
44     @param template: Contains the name of a template found in django
45      C{TEMPLATE_DIRS}
46     @type template: C{str}
47
48     @param extra: Extra variables to be passed to the context being built.
49     @type extra: C{dict}
50     """
51     news = Noticia.objects.order_by('-data_criacao')
52     menus = Menu.objects.all()
53     index_sections = Secao.objects.filter(index=True)
54     c = {'news': news, 'menu': menus,
55         'index_sections': index_sections}
56     c.update(extra)
57     return render_to_response(template, Context(c),
58             context_instance=RequestContext(request))
59
60
61 @enable_login_form
62 def index(request):
63     return build_response(request, 'index.html')
64
65
66 @transaction.commit_manually
67 @enable_login_form
68 def cadastro_palestrante(request):
69     form = CadastroPalestrante(request.POST or None)
70     ok = False
71     if request.POST and form.is_valid():
72         cd = form.cleaned_data
73         badattr = form.errors
74         wrong = False
75
76         if not cd['telefone'] and not cd['celular']:
77             badattr['telefone_comercial'] = ['Algum número de telefone '
78                                              'precisa ser informado']
79             wrong = True
80
81         # don't save duplicated users...
82         try:
83             User.objects.get(username=cd['nome_usuario'])
84             badattr['nome_usuario'] = ['Este nome de usuário já existe!']
85             wrong = True
86             transaction.rollback()
87         except User.DoesNotExist:
88             pass
89
90         if cd['senha'] != cd['senha_2']:
91             badattr['senha_2'] = ['A senha não confere']
92             wrong = True
93             transaction.rollback()
94
95         if not wrong:
96             group = Group.objects.get_or_create(name='palestrantes')[0]
97
98             user = User(username=cd['nome_usuario'], email=cd['email'])
99             user.set_password(cd['senha'])
100             user.is_active = False
101             user.save()
102             user.groups.add(group)
103
104             p = Palestrante()
105             p.usuario = user
106
107             p.nome = cd['nome_completo']
108             p.email = cd['email']
109             p.telefone = cd['telefone']
110             p.celular = cd['celular']
111             p.instituicao = cd['instituicao']
112             p.rua = cd['rua']
113             p.numero = cd['numero']
114             p.bairro = cd['bairro']
115             p.cidade = cd['cidade']
116             p.uf = cd['uf']
117             p.minicurriculo = cd['minicurriculo']
118             p.curriculo = cd['curriculo']
119             p.save()
120
121             for i in cd.get('area_interesse', []):
122                 p.area_interesse.add(i)
123
124             pid = p.id
125             md5_email = sha.new(cd['email']).hexdigest()
126             email = '%s <%s>' % (cd['nome_completo'], cd['email'])
127             link = '%s/verificar?c=%s&c1=%s' % (get_host(request),
128                     pid, md5_email)
129             t = loader.get_template('email-palestrante.html')
130             c = Context(dict(fulano=['nome_usuario'], link=link))
131             try:
132                 m = EmailMessage('Encontro Mineiro de Software Livre',
133                     t.render(c), FROM_EMAIL, [email])
134                 m.send()
135             except Exception:
136                 badattr['email'] = ['Não pude enviar o email de confirmação']
137                 transaction.rollback()
138             else:
139                 ok = True
140                 transaction.commit()
141
142     c = {'form': form, 'ok': ok}
143     return build_response(request, 'cadastro.html', c)
144
145
146 @enable_login_form
147 def inscricao(request):
148     post = request.POST
149     post2 = 'post2' in post and post or None
150
151     # exibe o formulário de inscrição de estudantes.
152     if 'estudante' in post:
153         form = InscricaoEstudante(post2)
154
155     # inscrição normal (sem ser estudante)
156     elif not 'estudante' in post and ('first_step' in post or 'empresa' in post):
157         form = InscricaoNormal(post2)
158
159     # primeiro passo...
160     else:
161         form = Inscricao(post or None)
162
163     return build_response(request, 'inscricao.html', {'form': form})
164
165
166 @login_required
167 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
168 def submeter_trabalho(request):
169     form = SubmeterTrabalho(request, request.POST or None)
170     ok = False
171
172     if request.POST and form.is_valid():
173         cd = form.cleaned_data
174         t = Trabalho()
175         t.titulo = cd['titulo']
176         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
177         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
178         t.descricao_curta = cd['descricao_curta']
179         t.descricao_longa = cd['descricao_longa']
180         t.recursos = cd['recursos']
181         t.evento = Evento.objects.get(pk=1) # let the hammer play arround!
182         t.save()
183
184         logged_in = request.user.palestrante_set.get()
185         t.palestrante.add(logged_in)
186         for i in cd.get('outros_palestrantes', []):
187             up = Palestrante.objects.get(pk=int(i))
188             t.palestrante.add(up)
189         ok = True
190
191     c = {'form': form, 'ok': ok}
192     return build_response(request, 'inscrever_palestra.html', c)
193
194
195 @login_required
196 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
197 def meus_trabalhos(request):
198     try:
199         p = Palestrante.objects.get(usuario=request.user)
200     except Palestrante.DoesNotExist:
201         # não palestrante...
202         c = {'palestrante': 0}
203         return build_response(request, 'meus_trabalhos.html', c)
204
205     t = Trabalho.objects.filter(palestrante=p)
206     c = {'trabalhos': t, 'palestrante': 1}
207     return build_response(request, 'meus_trabalhos.html', c)
208
209 @login_required
210 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
211 def editar_trabalho(request,codigo):
212     try:
213         p = Palestrante.objects.get(usuario=request.user)
214     except Palestrante.DoesNotExist:
215         # não palestrante...
216         c = {'palestrante': 0}
217         return build_response(request, 'meus_trabalhos.html', c)
218     trabalho = get_object_or_404(Trabalho, id=codigo,palestrante=p)
219     Formulario = form_for_instance(trabalho)
220     if request.method == 'POST':
221         form = Formulario(request.POST)
222         if form.is_valid():
223             form.save()
224             t = Trabalho.objects.filter(palestrante=p)
225             c = {'trabalhos': t, 'palestrante': 1}
226             c['editado_sucesso']=trabalho.titulo
227             return build_response(request, 'meus_trabalhos.html', c)
228     else:
229         form = Formulario()
230     
231     c = {'formulario':form}
232     return build_response(request, 'editar_trabalho.html', c)
233
234 @login_required
235 def meus_dados(request):
236     form = EditarPalestrante(request.POST or None)
237     palestrante = request.user.palestrante_set.get()
238     ok = False
239
240     for name, field in form.fields.items():
241         field.initial = getattr(palestrante, name)
242
243     if request.POST and form.is_valid():
244         cd = form.cleaned_data
245         for name, field in form.fields.items():
246             setattr(palestrante, name, cd[name])
247         palestrante.save()
248         ok = True
249
250     c = {'form': form, 'ok': ok}
251     return build_response(request, 'editar_palestrante.html', c)
252
253
254 @enable_login_form
255 def chamada_trabalhos(request):
256     return build_response(request, 'chamada_trabalhos.html')
257
258 @enable_login_form
259 def avaliacao(request):
260     return build_response(request, 'avaliacao.html')