User Authentication With Django Default Authentication System

written on Aug 27, 2014 by

Please note, this post is for django 1.6. Assume we have a project level urls.py ready like this:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from some_app.views import Some_class_based_view
admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', Some_class_based_view.as_view(), name='home'),
)

All we need to do is to put below two lines in the urls.py as we are using django's default views from django.contrib.auth:

url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^logout/$', 'django.contrib.auth.views.logout'),

After taking care of url mapping, the only thing left is to create templates for login and logout pages since Django provides no default template for the authentication views. Because we are uing views provided by django, and django's views will look for login.html and logged_out.html in templates/registration directory, we need to create a registration directory inside templates directory and put login.html and logged_out.html in it. So now the structure will look like this:

├── your project
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
├── manage.py
├── some_app
│   ├── __init__.py
│   ├── admin.py
│   ├── models.py
│   ├── tests.py
│   ├── views.py
└── templates
    ├── base.html
    ├── some_app
    │   └── some_list.html
    └── registration
        ├── logged_out.html
        └── login.html

Lastly, here is some basic templates you can start with.

login.html:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}

The hidden next field allows the view to redirect the user to the page requested, if the login request was triggered by a permission failure.

base.html:

<html>
<head>
  <title>some title</title>
</head>
<body>

<header>
  <p>
    {{ user }}
    {% if user.is_anonymous %}
    <a href="{% url 'django.contrib.auth.views.login' %}">login</a>
    {% else %}
    <a href="{% url 'django.contrib.auth.views.logout' %}">logout</a>
    {% endif %}
  </p>
</header>

<a href="{% url 'home' %}">
<h1>title</h1>
</a>
{% block content %}
{% endblock %}

</body>
</html>
comments powered by Disqus
 

Categories