Django Tutorial - Video 6 - User Authentication part 1

This tutorial covers the AUTH_PROFILE_MODULE. It covers creating user profiles for authentication.


drinker/models.py

from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User

class Drinker(models.Model):
        user            = models.OneToOneField(User)
        birthday        = models.DateField()
        name            = models.CharField(max_length=100)

        def __unicode__(self):
                return self.name
		

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
		

drinker/admin.py

from django.contrib import admin
from drinker.models import Drinker

admin.site.register(Drinker)
		

drinker/views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from drinker.forms import RegistrationForm

def DrinkerRegistration(request):
        if request.user.is_authenticated():
                return HttpResponseRedirect('/profile/')
        if request.method == 'POST':
                pass
        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))
		

templates/register.html

{% extends "base.html" %}
{% block content %}
{{ form }}
{% endblock %}
		

Add URL hook in urls.py

(r'^register/$', 'drinker.views.DrinkerRegistration'),
		

Add drinker to INSTALLED_APPS in settings.py

Add AUTH_PROFILE_MODULE to settings.py

# provide our get_profile()
AUTH_PROFILE_MODULE = 'drinker.Drinker'