Part 7: Django Login, Logout & Registration

Login form:
Adapted from theĀ login tutorial at techand startup.
Create a new app called ‘accounts’

$ python startapp accounts

Add ‘accounts’ to


Go to crudProject/ and add to the top of the file,

from django.shortcuts import render_to_response

Below that add,

def loggedin(request):
return render_to_response('registration/loggedin.html')

If you want to show their username when they login then call their username in the view. Change the loggedin function to:

def loggedin(request):
return render_to_response('registration/loggedin.html',
{'username': request.user.username})

Add the following urls to crudProject/

 # Auth-related URLs:
url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^accounts/loggedin/$', 'crudProject.views.loggedin', name='loggedin'),

To the bottom of crudProject/ add,

LOGIN_REDIRECT_URL = '/accounts/loggedin/'

Add login and logout buttons to index.html

<a href="/accounts/logout">logout</a>
<a href="/accounts/login">login</a>

Create a ‘registration’ directory in templates and add ‘login.html’

{% extends "index.html" %}
{% block title %}Log In{% endblock %}
{% block content %}

<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
{{ form.as_table }}

<input type="submit" value="login" />

{% endblock %}

In templates/registration/loggedin.html put,

{% extends "index.html" %}
{% block title %}Logged In{% endblock %}
{% block content %}

<h1>Welcome {{username}}</h1>
<p>Thank you for logging in.</p>
<p><a href="/accounts/logout/">Logout</a></p>

{% endblock %}

The create templates/registration/logged_out.html

{% extends "index.html" %}
{% block title %}Logged Out{% endblock %}
{% block content %}

<h2>Logged out!</h2>
<p><a href="/accounts/login/">Log back in</a></p>

{% endblock %}

User Registration:
Add to crudProject/

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth.forms import UserCreationForm
from django.core.context_processors import csrf

def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/accounts/register/complete')

form = UserCreationForm()
token = {}
token['form'] = form

return render_to_response('registration/registration_form.html', token)

def registration_complete(request):
return render_to_response('registration/registration_complete.html')

Add to crudProject/

# Registration URLs
url(r'^accounts/register/$', 'crudProject.views.register', name='register'),
url(r'^accounts/register/complete/$', 'crudProject.views.registration_complete', name='registration_complete'),