Django Tutorial - Video 7 - User Authentication part 2

This tutorial covers logging users in and out using djangos built in authentication backend.


drinker/views.py

from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from drinker.forms import RegistrationForm, LoginForm
from drinker.models import Drinker
from django.contrib.auth import authenticate, login, logout

def DrinkerRegistration(request):
        if request.user.is_authenticated():
                return HttpResponseRedirect('/profile/')
        if request.method == 'POST':
                form = RegistrationForm(request.POST)
                if form.is_valid():
                        user = User.objects.create_user(username=form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'])
                        user.save()
                        drinker = Drinker(user=user, name=form.cleaned_data['name'], birthday=form.cleaned_data['birthday'])
                        drinker.save()
                        return HttpResponseRedirect('/profile/')
                else:
                        return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
        else:
                ''' user is not submitting the form, show them a blank registration form '''
                form = RegistrationForm()
                context = {'form': form}
                return render_to_response('register.html', context, context_instance=RequestContext(request))

def LoginRequest(request):
        if request.user.is_authenticated():
                return HttpResponseRedirect('/profile/')
        if request.method == 'POST':
                form = LoginForm(request.POST)
                if form.is_valid():
                        username = form.cleaned_data['username']
                        password = form.cleaned_data['password']
                        drinker = authenticate(username=username, password=password)
                        if drinker is not None:
                                login(request, drinker)
                                return HttpResponseRedirect('/profile/')
                        else:
                                return render_to_response('login.html', {'form': form}, context_instance=RequestContext(request))
                else:
                        return render_to_response('login.html', {'form': form}, context_instance=RequestContext(request))
        else:
                ''' user is not submitting the form, show the login form '''
                form = LoginForm()
                context = {'form': form}
                return render_to_response('login.html', context, context_instance=RequestContext(request))

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

drinker/forms.py

from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from drinker.models import Drinker

class RegistrationForm(ModelForm):
        username        = forms.CharField(label=(u'User Name'))
        email           = forms.EmailField(label=(u'Email Address'))
        password        = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
        password1       = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))

        class Meta:
                model = Drinker
                exclude = ('user',)

        def clean_username(self):
                username = self.cleaned_data['username']
                try:
                        User.objects.get(username=username)
                except User.DoesNotExist:
                        return username
                raise forms.ValidationError("That username is already taken, please select another.")

        def clean(self):
                if self.cleaned_data['password'] != self.cleaned_data['password1']:
                        raise forms.ValidationError("The passwords did not match.  Please try again.")
                return self.cleaned_data

class LoginForm(forms.Form):
        username        = forms.CharField(label=(u'User Name'))
        password        = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
		

templates/register.html

{% extends "base.html" %}
{% block extrahead %}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.js" type="text/javascript"></script>
        <script>
        $(function() {
                $( "#id_birthday" ).datepicker();
        });
        </script>
{% endblock %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{% if form.errors %}<p>Please correct the following fields:</p>{% endif %}
<div class="register_div">
        {% if form.username.errors %}<p class="error">{{ form.username.errors }}</p>{% endif %}
        <p><label for="username"{% if form.username.errors %} class="error"{% endif %}>Username:</label></p>
        <p>{{ form.username }}</p>
</div>
<div class="register_div">
        {% if form.email.errors %}<p class="error">{{ form.email.errors }}</p>{% endif %}
        <p><label for="email"{% if form.email.errors %} class="error"{% endif %}>Email:</label></p>
        <p>{{ form.email }}</p>
</div>
<div class="register_div">
        {% if form.password.errors %}<p class="error">{{ form.password.errors }}</p>{% endif %}
        <p><label for="password"{% if form.password.errors %} class="error"{% endif %}>Password:</label></p>
        <p>{{ form.password }}</p>
</div>
<div class="register_div">
        {% if form.password1.errors %}<p class="error">{{ form.password1.errors }}</p>{% endif %}
        <p><label for="password1"{% if form.password1.errors %} class="error"{% endif %}>Verify Password:</label></p>
        <p>{{ form.password1 }}</p>
</div>
<div class="register_div">
        {% if form.birthday.errors %}<p class="error">{{ form.birthday.errors }}</p>{% endif %}
        <p><label for="birthday"{% if form.birthday.errors %} class="error"{% endif %}>Birthday:</label></p>
        <p>{{ form.birthday }}</p>
</div>
<div class="register_div">
        {% if form.name.errors %}<p class="error">{{ form.name.errors }}</p>{% endif %}
        <p><label for="name"{% if form.name.errors %} class="error"{% endif %}>Name:</label></p>
        <p>{{ form.name }}</p>
</div>
<p><input type="submit" alt="register" /></p>
</form>
{% endblock %}
		

templates/base.html

<html>
<head>
        <link rel="stylesheet" type="text/css" href="/static/css/video1.css" />
        {% block extrahead %}{% endblock %}
</head>
<body>
<div id="pageContainer">
        <div id="nav_top_right">
                {% if user.is_authenticated %}<p><a href="/logout/">Logout</a></p>{% else %}<p><a href="/login/">Login</a></p>{% endif %}
        </div>
        {% block content %}
        {% endblock %}
</div>
</body>
</html>
		

templates/login.html

{% extends "base.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{% if form.errors %}<p>Please correct the following fields:</p>{% endif %}
<div class="register_div">
        {% if form.username.errors %}<p class="error">{{ form.username.errors }}</p>{% endif %}
        <p><label for="username"{% if form.username.errors %} class="error"{% endif %}>Username:</label></p>
        <p>{{ form.username }}</p>
</div>
<div class="register_div">
        {% if form.password.errors %}<p class="error">{{ form.password.errors }}</p>{% endif %}
        <p><label for="password"{% if form.password.errors %} class="error"{% endif %}>Password:</label></p>
        <p>{{ form.password }}</p>
</div>
<p><input type="submit" alt="register" /></p>
</form>
<p>Forgot your password? <a href="/resetpassword/">Reset it!</a></p>
{% endblock %}