十四 Django 1.5.4 用户注册

一.forms.py

from django import forms
from django.contrib.auth.models import User

class ContactForm(forms.Form):
        Email        = forms.EmailField(widget=forms.TextInput())
        Titulo        = forms.CharField(widget=forms.TextInput())
        Texto        = forms.CharField(widget=forms.Textarea())

class LoginForm(forms.Form):
        username = forms.CharField(widget=forms.TextInput())
        password = forms.CharField(widget=forms.PasswordInput(render_value=False))


class RegisterForm(forms.Form):
        username = forms.CharField(label="Nombre de Usuario",widget=forms.TextInput())
        email = forms.EmailField(label="Correo Electronico",widget=forms.TextInput())
        password_one = forms.CharField(label="Password",widget=forms.PasswordInput(render_value=False))
        password_two = forms.CharField(label="Confirmar password",widget=forms.PasswordInput(render_value=False))

        def clean_username(self):
                username = self.cleaned_data['username']
                try:
                        u = User.objects.get(username=username)
                except User.DoesNotExist:
                        return username
                raise forms.ValidationError('Nombre de usuario ya existe')

        def clean_email(self):
                email = self.cleaned_data['email']
                try:
                        u = User.objects.get(email=email)
                except User.DoesNotExist:
                        return email
                raise forms.ValidationError('Email ya registrado')

        def clean_password_two(self):
                password_one = self.cleaned_data['password_one']
                password_two = self.cleaned_data['password_two']
                if password_one == password_two:
                        pass
                else:
                        raise forms.ValidationError('Password no coinciden')

二.urls.py

from django.conf.urls.defaults import patterns,url


urlpatterns = patterns('demo.apps.home.views',
        url(r'^$','index_view',name='vista_principal'),
        url(r'^about/$','about_view',name='vista_about'),
        url(r'^productos/page/(?P<pagina>.*)/$','productos_view',name='vista_productos'),
        url(r'^producto/(?P<id_prod>.*)/$','singleProduct_view',name='vista_single_producto'),
        url(r'^contacto/$','contacto_view',name='vista_contacto'),
        url(r'^login/$','login_view',name='vista_login'),
        url(r'^registro/$','register_view',name='vista_registro'),
        url(r'^logout/$','logout_view',name='vista_logout'),
)

三.views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from demo.apps.ventas.models import producto
from demo.apps.home.forms import ContactForm, LoginForm,RegisterForm
from django.core.mail import EmailMultiAlternatives # Enviamos HTML
from django.contrib.auth.models import User

from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
# Paginacion en Django
from django.core.paginator import Paginator,EmptyPage,InvalidPage

def index_view(request):
        return render_to_response('home/index.html',context_instance=RequestContext(request))

def about_view(request):
        mensaje = "Esto es un mensaje desde mi vista"
        ctx = {'msg':mensaje}
        return render_to_response('home/about.html',ctx,context_instance=RequestContext(request))

def productos_view(request,pagina):
        lista_prod = producto.objects.filter(status=True) # Select * from ventas_productos where status = True
        paginator = Paginator(lista_prod,5) # Cuantos productos quieres por pagina? = 3
        try:
                page = int(pagina)
        except:
                page = 1
        try:
                productos = paginator.page(page)
        except (EmptyPage,InvalidPage):
                productos = paginator.page(paginator.num_pages)
        ctx = {'productos':productos}
        return render_to_response('home/productos.html',ctx,context_instance=RequestContext(request))

def singleProduct_view(request,id_prod):
        prod = producto.objects.get(id=id_prod)
        cats = prod.categorias.all() # Obteniendo las categorias del producto encontrado
        ctx = {'producto':prod,'categorias':cats}
        return render_to_response('home/SingleProducto.html',ctx,context_instance=RequestContext(request))


def contacto_view(request):
        info_enviado = False # Definir si se envio la informacion o no se envio
        email = ""
        titulo = ""
        texto = ""
        if request.method == "POST":
                formulario = ContactForm(request.POST)
                if formulario.is_valid():
                        info_enviado = True
                        email = formulario.cleaned_data['Email']
                        titulo = formulario.cleaned_data['Titulo']
                        texto = formulario.cleaned_data['Texto']

                        # Configuracion enviando mensaje via GMAIL
                        to_admin = '[email protected]'
                        html_content = "Informacion recibida de [%s] <br><br><br>***Mensaje****<br><br>%s"%(email,texto)
                        msg = EmailMultiAlternatives('Correo de Contacto',html_content,'[email protected]',[to_admin])
                        msg.attach_alternative(html_content,'text/html') # Definimos el contenido como HTML
                        msg.send() # Enviamos en correo
        else:
                formulario = ContactForm()
        ctx = {'form':formulario,'email':email,'titulo':titulo,'texto':texto,'info_enviado':info_enviado}
        return render_to_response('home/contacto.html',ctx,context_instance=RequestContext(request))


def login_view(request):
        mensaje = ""
        if request.user.is_authenticated():
                return HttpResponseRedirect('/')
        else:
                if request.method == "POST":
                        form = LoginForm(request.POST)
                        if form.is_valid():
                                username = form.cleaned_data['username']
                                password = form.cleaned_data['password']
                                usuario = authenticate(username=username,password=password)
                                if usuario is not None and usuario.is_active:
                                        login(request,usuario)
                                        return HttpResponseRedirect('/')
                                else:
                                        mensaje = "usuario y/o password incorrecto"
                form = LoginForm()
                ctx = {'form':form,'mensaje':mensaje}
                return render_to_response('home/login.html',ctx,context_instance=RequestContext(request))

def logout_view(request):
        logout(request)
        return HttpResponseRedirect('/')

def register_view(request):
        form = RegisterForm()
        if request.method == "POST":
                form = RegisterForm(request.POST)
                if form.is_valid():
                        usuario = form.cleaned_data['username']
                        email = form.cleaned_data['email']
                        password_one = form.cleaned_data['password_one']
                        password_two = form.cleaned_data['password_two']
                        u = User.objects.create_user(username=usuario,email=email,password=password_one)
                        u.save() # Guardar el objeto
                        return render_to_response('home/thanks_register.html',context_instance=RequestContext(request))
                else:
                        ctx = {'form':form}
                        return         render_to_response('home/register.html',ctx,context_instance=RequestContext(request))
        ctx = {'form':form}
        return render_to_response('home/register.html',ctx,context_instance=RequestContext(request))

login.html

{% extends "base.html" %}
{% block title %} Login {% endblock %}
{% block content %}
<form action="." method="POST">
        {% csrf_token %}
        {{ mensaje }}
        {{ form.as_p }}
        <button class="btn btn-primary" type="submit"> Login </button>
        <h5>Registrarte <a href="/registro/">aquí</a></h5>
</form>

{% endblock %}

register.html

{% extends "base.html" %}
{% block title %} Registro {% endblock %}
{% block content %}
<form action="." method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button class="btn btn-primary" type="submit"> Registrar </button>
</form>

{% endblock %}

thanks_register.html

{% extends "base.html" %}
{% block title %} Registro {% endblock %}
{% block content %}
<h2> Gracias por registrarte!!! </h2>
<a href="/login/" class="btn btn-primary"> Iniciar Sesion </a>
{% endblock %}
十四 Django 1.5.4 用户注册_第1张图片






你可能感兴趣的:(django)