implementing lecturer registration feature
authorLincoln de Sousa <lincoln@minaslivre.org>
Wed, 2 Jul 2008 00:39:11 +0000 (21:39 -0300)
committerLincoln de Sousa <lincoln@minaslivre.org>
Wed, 2 Jul 2008 00:39:11 +0000 (21:39 -0300)
eventos/forms.py
eventos/templates/eventos/lecturer-add.html [new file with mode: 0644]
eventos/urls.py
eventos/views.py
templates/base.html

index 8e3980e..3c8acea 100644 (file)
 # 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 import newforms as forms
+from django.newforms import PasswordInput, ValidationError
+from django.contrib.auth.models import User
+
+
+class RegisterLecturer(forms.Form):
+    username = forms.CharField(max_length=20, label=u'Usuário para login')
+    password1 = forms.CharField(widget=PasswordInput, label='Senha')
+    password2 = forms.CharField(widget=PasswordInput, label='Confirmar Senha')
+
+    def clean_password2(self):
+        if self.cleaned_data['password1'] != self.cleaned_data['password2']:
+            raise ValidationError('A confirmação não confere com a senha')
+        return self.cleaned_data['password2']
+
+    def clean_username(self):
+        try:
+            User.objects.get(username=self.cleaned_data['username'])
+            raise ValidationError('Já existe um usuário com esse nome')
+        except User.DoesNotExist:
+            return self.cleaned_data['username']
diff --git a/eventos/templates/eventos/lecturer-add.html b/eventos/templates/eventos/lecturer-add.html
new file mode 100644 (file)
index 0000000..79d026e
--- /dev/null
@@ -0,0 +1,11 @@
+{% extends "base.html" %}
+
+{% block content %}
+<form id="lecturer-details" method="post" action="./">
+  {{ uform.as_p }}
+
+  {{ form.as_p }}
+
+  <input type="submit" value="Ok" />
+</form>
+{% endblock %}
index 35bb882..b0637a2 100644 (file)
@@ -3,6 +3,7 @@ from django.conf.urls.defaults import *
 urlpatterns = patterns('',
     (r'^login/', 'eventos.views.login'),
     (r'^logout/', 'eventos.views.logout'),
+    (r'^lecturer/add/$', 'eventos.views.lecturer_add'),
     (r'^lecturer/(\d+)/$', 'eventos.views.lecturer_details'),
     (r'^lecturer/(\d+)/talks/$', 'eventos.views.lecturer_talks'),
     (r'^talks/(\d+)/$', 'eventos.views.talk_details'),
index 98a1f92..b5ab128 100644 (file)
 from django.http import HttpResponseRedirect, HttpResponseForbidden
 from django.contrib import auth
 from django.contrib.auth.forms import AuthenticationForm
-from django.newforms import form_for_instance, form_for_model, HiddenInput
+from django.contrib.auth.models import User, Group
+from django.newforms import form_for_instance, form_for_model
 from django.shortcuts import render_to_response, get_object_or_404
 from django.template import RequestContext, Context, loader
 from eventos.models import Palestrante, Trabalho
+from eventos.forms import RegisterLecturer
 
 forbidden = \
     HttpResponseForbidden('<h2>You are not allowed to do this action.<h2>')
@@ -59,6 +61,39 @@ def logout(request):
     auth.logout(request)
     return HttpResponseRedirect('/')
 
+def lecturer_add(request):
+    """Adds a new lecturer to the system.
+    """
+    uform = RegisterLecturer(request.POST or None)
+
+    FormKlass = form_for_model(Palestrante)
+    form = FormKlass(request.POST or None)
+    del form.fields['usuario']
+
+    if request.POST and form.is_valid() and uform.is_valid():
+        cd = uform.cleaned_data
+        group = Group.objects.get_or_create(name='palestrantes')[0]
+
+        # creating the user that will be set as the user of the
+        # lecturer.
+        user = User(username=cd['username'])
+        user.set_password(cd['password1'])
+        user.is_active = True
+        user.save()
+        user.groups.add(group)
+
+        # this commit=False is to avoid IntegritErrors, because at
+        # this point, the lecturer doesn't have an user associated
+        # with it.
+        instance = form.save(commit=False)
+        instance.usuario = user
+        instance.save()
+        return HttpResponseRedirect('/')
+
+    c = {'form': form, 'uform': uform}
+    return render_to_response('eventos/lecturer-add.html', Context(c),
+                              context_instance=RequestContext(request))
+
 def lecturer_details(request, lid):
     """Shows a simple form containing all editable fields of a
     lecturer and gives the lecturer the possibility to save them =)
index 4f285c7..d2afc6d 100644 (file)
@@ -43,7 +43,7 @@
       <li><a href="/logout">Sair</a></li>
 
       {% else %}
-      <li><a href="/cadastro-palestrante">Cadastre-se para enviar trabalhos</a></li>
+      <li><a href="/lecturer/add/">Cadastre-se para enviar trabalhos</a></li>
       <li><a href="/cadastro-participante">Cadastre-se para participar</a></li>
       {% endif %}
     </ul>