X-Git-Url: http://git.cascardo.eti.br/?a=blobdiff_plain;f=views.py;h=ee7b1b3104548609615267648c7613c583991966;hb=3a2dcbf3086e01646891a1365730c3604c431792;hp=1d973745a9110ec1e9100c5c7ae6e173ec512e7f;hpb=b4ceb1def210ed357e3cd138512802b0575a4a0d;p=cascardo%2Feventmanager.git diff --git a/views.py b/views.py index 1d97374..ee7b1b3 100644 --- a/views.py +++ b/views.py @@ -1,4 +1,4 @@ -# -*- coding: utf8; -*- +# -*- coding: utf-8; -*- """ Copyright (C) 2007 Lincoln de Sousa @@ -17,125 +17,280 @@ License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ -from django.shortcuts import render_to_response -from django.template import RequestContext, Context -from django.contrib.auth.decorators import login_required +from django.shortcuts import render_to_response, get_object_or_404 +from django.template import RequestContext, Context, loader +from django.contrib.auth.decorators import login_required, user_passes_test from django.contrib.auth.models import Group, User -from django.contrib.auth.forms import AuthenticationForm -from django.contrib.auth import login +from django.newforms import form_for_instance +from django.core.mail import EmailMessage +from django.db import transaction +from django.http import get_host from eventmanager.decorators import enable_login_form -from eventmanager.forms import InscreverPalestra, CadastroPalestrante +from eventmanager.forms import * from eventmanager.conteudo.models import Noticia, Menu, Secao from eventmanager.eventos.models import * +import sha -@enable_login_form -def index(request): +FROM_EMAIL = 'Emsl 2007 ' + +def build_response(request, template, extra={}): + """ + Shortcut to build a response based on a C{template} and build a standard + context to this template. This context contains news itens, a list of menus + and a list of sections to be shown on index. But don't worry, this context + is extensible through the C{extra} parameter. + + @param template: Contains the name of a template found in django + C{TEMPLATE_DIRS} + @type template: C{str} + + @param extra: Extra variables to be passed to the context being built. + @type extra: C{dict} + """ news = Noticia.objects.order_by('-data_criacao') menus = Menu.objects.all() index_sections = Secao.objects.filter(index=True) - - c = Context({'news': news, 'menu': menus, - 'index_sections': index_sections}) - return render_to_response('index.html', c, + login_failed = 'login_failed' in request.GET + c = {'news': news, 'menu': menus, + 'index_sections': index_sections, + 'login_failed': login_failed} + c.update(extra) + return render_to_response(template, Context(c), context_instance=RequestContext(request)) @enable_login_form -def cadastro(request): - # context extension - c = {} - - if request.POST: - # django's newforms lib requires a new instance of a form to be bounded - # with data, to be validated and used. - form = CadastroPalestrante(request.POST) - if form.is_valid(): - cd = form.cleaned_data - wrong = False +def index(request): + return build_response(request, 'index.html') + + +@transaction.commit_manually +@enable_login_form +def cadastro_palestrante(request): + form = CadastroPalestrante(request.POST or None) + ok = False + if request.POST and form.is_valid(): + cd = form.cleaned_data + badattr = form.errors + wrong = False + + if not cd['telefone'] and not cd['celular']: + badattr['telefone_comercial'] = \ + ['Algum número de telefone precisa ser informado'] + wrong = True + + # don't save duplicated users... + try: + User.objects.get(username=cd['nome_usuario']) + badattr['nome_usuario'] = ['Este nome de usuário já existe!'] + wrong = True + transaction.rollback() + except User.DoesNotExist: + pass + + if cd['senha'] != cd['senha_2']: + badattr['senha_2'] = ['A senha não confere'] + wrong = True + transaction.rollback() + + if not wrong: + group = Group.objects.get_or_create(name='palestrantes')[0] - # XXX: really ugly hack to use django validation machinary... - badattr = form._BaseForm__errors + user = User(username=cd['nome_usuario'], email=cd['email']) + user.set_password(cd['senha']) + user.is_active = False + user.save() + user.groups.add(group) - if not cd['telefone_comercial'] and \ - not cd['telefone_residencial'] and \ - not cd['telefone_celular']: - badattr['telefone_comercial'] = ['Algum número de telefone ' - 'precisa ser informado'] - wrong = True + p = Palestrante() + p.usuario = user - # don't save duplicated users... + p.nome = cd['nome_completo'] + p.email = cd['email'] + p.telefone = cd['telefone'] + p.celular = cd['celular'] + p.instituicao = cd['instituicao'] + p.rua = cd['rua'] + p.numero = cd['numero'] + p.bairro = cd['bairro'] + p.cidade = cd['cidade'] + p.uf = cd['uf'] + p.minicurriculo = cd['minicurriculo'] + p.curriculo = cd['curriculo'] + p.save() + + for i in cd.get('area_interesse', []): + p.area_interesse.add(i) + + pid = p.id + md5_email = sha.new(cd['email']).hexdigest() + email = '%s <%s>' % (cd['nome_completo'], cd['email']) + link = '%s/verificar?c=%s&c1=%s' % (get_host(request), + pid, md5_email) + t = loader.get_template('email-palestrante.html') + c = Context(dict(fulano=['nome_usuario'], link=link)) try: - User.objects.get(username=cd['nome_usuario']) - badattr['nome_usuario'] = ['Este nome de usuário já existe!'] - wrong = True - except User.DoesNotExist: - pass - - if not wrong: - group = Group.objects.get_or_create(name='palestrantes')[0] - - p = Palestrante() - p.user = User(username=cd['nome_usuario'], email=cd['email']) - p.user.set_password(cd['senha']) - p.user.save() - p.user.groups.add(group) - - p.nome = cd['nome_completo'] - p.email = cd['email'] - p.telefone_comercial = cd['telefone_comercial'] - p.telefone_residencial = cd['telefone_residencial'] - p.telefone_celular = cd['telefone_celular'] - p.rua = cd['rua'] - p.numero = cd['numero'] - p.bairro = cd['bairro'] - p.cidade = cd['cidade'] - p.uf = cd['uf'] - p.minicurriculo = cd['minicurriculo'] - p.save() - - for i in cd['area_interesse']: - p.area_interesse.add(i) - - c.update({'ok': 1}) - - fakepost = request.POST.copy() - fakepost['username'] = cd['nome_usuario'] - fakepost['password'] = cd['senha'] - - manipulator = AuthenticationForm(request) - errors = manipulator.get_validation_errors(fakepost) - got_user = manipulator.get_user() - login(request, got_user) - else: - form = CadastroPalestrante() + m = EmailMessage('Encontro Mineiro de Software Livre', + t.render(c), FROM_EMAIL, [email]) + m.send() + except Exception: + badattr['email'] = \ + ['Desculpe mas não pude enviar o email de confirmação'] + transaction.rollback() + else: + ok = True + transaction.commit() - c.update({'form': form}) - return render_to_response('cadastro.html', Context(c), - context_instance=RequestContext(request)) + c = {'form': form, 'ok': ok} + return build_response(request, 'cadastro.html', c) + + +@enable_login_form +def inscricao(request): + return build_response(request, 'inscricao.html') + + +@enable_login_form +@transaction.commit_manually +def inscricao_individual(request): + form = Inscricao(request.POST or None) + ok = False + if request.POST and form.is_valid(): + cd = form.cleaned_data + badattr = form.errors + wrong = False + + # don't save duplicated users... + try: + User.objects.get(username=cd['nome_usuario']) + badattr['nome_usuario'] = ['Este nome de usuário já existe!'] + wrong = True + transaction.rollback() + except User.DoesNotExist: + pass + + if cd['senha'] != cd['senha_2']: + badattr['senha_2'] = ['A senha não confere'] + wrong = True + transaction.rollback() + + if not wrong: + group = Group.objects.get_or_create(name='participantes')[0] + + user = User(username=cd['nome_usuario'], email=cd['email']) + user.set_password(cd['senha']) + user.is_active = False + user.save() + user.groups.add(group) + + transaction.commit() + + return build_response(request, 'inscricao_individual.html', {'form': form}) + + +@enable_login_form +def inscricao_caravana(request): + form_coordenador = InscricaoCoordenador(request.POST or None) + form = InscricaoCaravana(request.POST or None) + return build_response(request, 'inscricao_caravana.html', + {'form_coordenador': form_coordenador, 'form': form}) @login_required -def inscrever_palestra(request): - c = {} - if request.POST: - form = InscreverPalestra(request.POST) - if form.is_valid(): - cd = form.cleaned_data - p = Palestra() - p.titulo = cd['titulo'] - p.tema = cd['tema'] - p.categoria = CategoriaPalestra.objects.get(pk=cd['categoria']) - p.descricao_curta = cd['descricao_curta'] - p.descricao_longa = cd['descricao_longa'] - p.evento = Evento.objects.get(pk=1) # let the hammer play arround! - p.save() +@user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/') +def submeter_trabalho(request): + form = SubmeterTrabalho(request, request.POST or None) + ok = False + + if request.POST and form.is_valid(): + cd = form.cleaned_data + t = Trabalho() + t.titulo = cd['titulo'] + t.tipo = TipoTrabalho.objects.get(pk=cd['tipo']) + t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0] + t.descricao_curta = cd['descricao_curta'] + t.descricao_longa = cd['descricao_longa'] + t.recursos = cd['recursos'] + t.evento = Evento.objects.get(pk=1) # let the hammer play arround! + t.save() + + logged_in = request.user.palestrante_set.get() + t.palestrante.add(logged_in) + for i in cd.get('outros_palestrantes', []): + up = Palestrante.objects.get(pk=int(i)) + t.palestrante.add(up) + ok = True + + c = {'form': form, 'ok': ok} + return build_response(request, 'inscrever_palestra.html', c) + + +@login_required +@user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/') +def meus_trabalhos(request): + try: + p = Palestrante.objects.get(usuario=request.user) + except Palestrante.DoesNotExist: + # não palestrante... + c = {'palestrante': 0} + return build_response(request, 'meus_trabalhos.html', c) + + t = Trabalho.objects.filter(palestrante=p) + c = {'trabalhos': t, 'palestrante': 1} + return build_response(request, 'meus_trabalhos.html', c) - up = User.objects.get(pk=request.user.id) - p.palestrante.add() + +@login_required +@user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/') +def editar_trabalho(request, codigo): + try: + p = Palestrante.objects.get(usuario=request.user) + except Palestrante.DoesNotExist: + # não palestrante... + c = {'palestrante': 0} + return build_response(request, 'meus_trabalhos.html', c) + trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p) + Formulario = form_for_instance(trabalho) + if request.method == 'POST': + form = Formulario(request.POST) + if form.is_valid(): + form.save() + t = Trabalho.objects.filter(palestrante=p) + c = {'trabalhos': t, 'palestrante': 1} + c['editado_sucesso']=trabalho.titulo + return build_response(request, 'meus_trabalhos.html', c) else: - form = InscreverPalestra() - c.update({'form': form}) + form = Formulario() + + c = {'formulario':form} + return build_response(request, 'editar_trabalho.html', c) - return render_to_response('inscrever_palestra.html', Context(c), - context_instance=RequestContext(request)) + +@login_required +def meus_dados(request): + form = EditarPalestrante(request.POST or None) + palestrante = request.user.palestrante_set.get() + ok = False + + for name, field in form.fields.items(): + field.initial = getattr(palestrante, name) + + if request.POST and form.is_valid(): + cd = form.cleaned_data + for name, field in form.fields.items(): + setattr(palestrante, name, cd[name]) + palestrante.save() + ok = True + + c = {'form': form, 'ok': ok} + return build_response(request, 'editar_palestrante.html', c) + + +@enable_login_form +def chamada_trabalhos(request): + return build_response(request, 'chamada_trabalhos.html') + +@enable_login_form +def avaliacao(request): + return build_response(request, 'avaliacao.html')