Anonymous avatar Anonymous committed 582de08

Criação e funcionamento do formulário de cadastro.

Comments (0)

Files changed (6)

+#coding:utf-8
+
+from django import forms
+from django.contrib.auth.forms import UserCreationForm
+from django.contrib.auth.models import User
+
+from models import Aluno
+from util.validacoes import validar_cpf
+
+class CPFField(forms.CharField):
+    def clean(self, value):
+        if not value:
+            raise forms.ValidationError('Este campo é obrigatório.')
+        cpf = value.replace('.', '').replace('-', '')
+        if not validar_cpf(cpf):
+            raise forms.ValidationError('Você deve digitar um CPF válido.')
+
+class AlunoForm(forms.ModelForm):
+    class Meta:
+        model = Aluno
+        fields = ('username', 'first_name', 'last_name', 'email', 'password')
+
+    cpf = CPFField(max_length = 15, widget = forms.TextInput())
+    password = forms.CharField(max_length = 16, min_length = 4, widget = forms.PasswordInput, label = 'Senha')
+    confirmacao_senha = forms.CharField(max_length = 16, min_length = 4, widget = forms.PasswordInput)
+
+    def clean_username(self):
+        if User.objects.filter(username = self.cleaned_data['username']).count() > 0:
+            raise forms.ValidationError('Já existe um usuário com este login.')
+
+        return self.cleaned_data['username']
+
+    def clean_email(self):
+        if User.objects.filter(email = self.cleaned_data['email']).count() > 0:
+            raise forms.ValidationError('Já existe um usuário com este e-mail.')
+
+        return self.cleaned_data['email']
+
+    def clean_confirmacao_senha(self):
+        if self.cleaned_data['confirmacao_senha'] != self.data['password']:
+            raise forms.ValidationError('A senha e a confirmação da senha não correspondem.')
+
+        return self.cleaned_data['confirmacao_senha']
+
+    def save(self, commit = True):
+        aluno = super(AlunoForm, self).save(commit = False)
+        aluno.set_password(self.cleaned_data['password'])
+
+        if commit:
+            aluno.save()
+
+        return aluno
             url(r'^$', 'cursos'),
             url(r'^(?P<slug>[\w_-]+)/$', 'curso'),
             url(r'^instrutores/(?P<slug>[\w_-]+)$', 'instrutor'),
-            url(r'^inscricao/(?P<slug>[\w_-]+)$', 'inscricao')
+            url(r'^inscricao/(?P<slug>[\w_-]+)$', 'inscricao'),
+            url(r'^alunos/cadastro/$', 'cadastro'),
+            url(r'^alunos/cadastrar/$', 'cadastrar'),
 )
+#coding:utf-8
 # Create your views here.
 from django.shortcuts import get_object_or_404
 from django.shortcuts import render_to_response
 from django.template import RequestContext
+from django.http import HttpResponse
 from django.contrib.auth.decorators import login_required
 from models import Instrutor, Curso
+from forms import AlunoForm
+
+def cursos(request):
+    cursos = Curso.objects.all()
+    return render_to_response('cursos.html', locals(), context_instance = RequestContext(request))
+
+def cadastro(request):
+    form = AlunoForm()
+    return render_to_response('cadastro_aluno.html', locals(), context_instance = RequestContext(request))
+
+def cadastrar(request):
+    if request.method == 'POST':
+        form = AlunoForm(request.POST)
+        if form.is_valid():
+            form.save()
+            msg = 'Cadastro efetuado com sucesso!'
+
+        return render_to_response('cadastro_aluno.html', locals(), context_instance = RequestContext(request))
+    else:
+        return HttpResponse('Esta página deve tratar um formulário, não acesse-a diretamente.')
 
 @login_required
 def instrutor(request, slug):
     curso = get_object_or_404(Curso, slug = slug)
     return render_to_response('curso.html', locals(), context_instance = RequestContext(request))
 
-def cursos(request):
-    cursos = Curso.objects.all()
-    return render_to_response('cursos.html', locals(), context_instance = RequestContext(request))
-
 @login_required
 def inscricao(request, slug):
     curso = get_object_or_404(Curso, slug = slug)
     return render_to_response('inscricao.html', locals(), context_instance = RequestContext(request))
+

templates/cadastro_aluno.html

+{% extends "super.html" %}
+
+{% block titulo %}{{ block.super }} - Cadastro de aluno{% endblock titulo %}
+
+{% block topo %}
+    <div align="center"><h1>Cadastro de usuário</h1></div>
+{% endblock topo %}
+
+{% block conteudo %}
+    {% if msg %}
+        <strong>{{ msg }}</strong>
+    {% else %}
+        {% if form.errors %}
+            <font color="red">Erros de validação:<br /><br /></font>
+            {% for campo in form %}
+                {% if campo.errors %}
+                    <br /><strong>{{ campo.label }}</strong> {{ campo.errors }}
+                {% endif %}
+            {% endfor %}
+        {% endif %}
+        <form method="post" action="{% url cursos.views.cadastrar %}">
+            <table class="table_form" cellpadding="2" cellspacing="0">
+                <tr>
+                    <td class="label_table_form">Nome:</td>
+                    <td class="wid_table_form">{{ form.first_name }}</td>
+                </tr>
+                <tr>
+                    <td class="label_table_form">Sobrenome:</td>
+                    <td class="wid_table_form">{{ form.last_name }}</td>
+                </tr>
+                <tr>
+                    <td class="label_table_form">E-mail:</td>
+                    <td class="wid_table_form">{{ form.email }}</td>
+                </tr>
+                <tr>
+                    <td class="label_table_form">Nome de usuário:</td>
+                    <td class="wid_table_form">{{ form.username }}</td>
+                </tr>
+                <tr>
+                    <td class="label_table_form">Senha:</td>
+                    <td class="wid_table_form">{{ form.password }}</td>
+                </tr>
+                <tr>
+                    <td class="label_table_form">Confirme a senha:</td>
+                    <td class="wid_table_form">{{ form.confirmacao_senha }}</td>
+                </tr>
+                <tr>
+                    <td class="label_table_form">CPF:</td>
+                    <td class="wid_table_form">{{ form.cpf }}</td>
+                </tr>
+                <tr>
+                    <td class="label_table_form">&nbsp;</td>
+                    <td class="submit_table_form"><input type="submit" value="Cadastrar" /></td>
+                </tr>
+            </table>
+        </form>
+    {% endif %}
+{% endblock conteudo %}

templates/super.html

                 {% if user.is_authenticated %}
                     <a href="{% url django.contrib.auth.views.logout %}">Sair do sistema</a> | 
                 {% else %}
-                    <a href="{% url django.contrib.auth.views.login %}">Entrar no sistema</a> | 
+                    <a href="{% url django.contrib.auth.views.login %}">Entrar no sistema</a> |
+                    <a href="{% url cursos.views.cadastro %}">Cadastrar-se</a> |  
                 {% endif %}
                 <a href="{% url views.bemvindo %}admin/" target="_blank">Administração</a>
             {% endblock menu %}

util/validacoes.py

+def calcular_digito(cpf, multiplicador):
+    multiplos = []
+    for x in cpf[:(multiplicador - 1)]:
+        multiplos.append(int(x) * multiplicador)
+        multiplicador -= 1
+
+    valor_raiz = sum(multiplos) % 11
+    return 0 if (valor_raiz < 2) else (11 - valor_raiz)
+
+def validar_cpf(cpf):
+    if len(cpf) != 11:
+        return False
+
+    primeiro_digito = int(cpf[9])
+    segundo_digito = int(cpf[10])
+
+    d1 = calcular_digito(cpf, 10)
+    d2 = calcular_digito(cpf, 11)
+
+    return d1 == primeiro_digito and d2 == segundo_digito
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.