Django auth/login problems

12,220

simple login/logout system could be find here

Let me briefly explain how to use standard auth through the user model in Django:

appname/views.py:

from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.template import Context, loader, RequestContext
from django.shortcuts import render_to_response
from django.template import 

@login_required
def stat_info(request):
return render_to_response('stat_info.html',
  {'is_auth':request.user.is_authenticated()},
  context_instance=RequestContext(request))

@login_required
def mainmenu(request):
return render_to_response('mainmenu.html',{},
  context_instance=RequestContext(request))

urls.py:

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

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    (r'^statinfo/$', 'appname.views.stat_info'),
    (r'^accounts/login/$', 'django.contrib.auth.views.login'),
    (r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page' : '/accounts/login'}),
    (r'^mainmenu/$', 'appname.views.mainmenu')
)

settings.py:

...        
LOGIN_REDIRECT_URL='/mainmenu/'
...

templates/registration/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 %}

templates/base.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}templates/base.html{% endblock %}</title>
</head>
<body>
<div id="sidebar">
    {% block sidebar %}
    <ul>
        <li><a href="/">Home</a></li>

        {% if user.is_authenticated %}
            <li><a href="/accounts/logout">Logout</a></li>
        {% else %}
            <li><a href="/accounts/login">Login</a></li>
        {% endif %}
    </ul>
    {% endblock %}
</div>
<div id="content">
    {% block content %}{% endblock %}
</div>
</body>
</html>

templates/mainmenu.html:

<!DOCTYPE html>
{% extends "base.html" %}
<html>
<head>
    <title>{% block title %}templates/mainmenu.html{% endblock %}</title>
</head>
<body>

<div id="content">
    {% block content %}
    Mainmenu
    <a href="/statinfo/">stat info</a>
    {% endblock %}

</div>

</body>
</html>

templates/stat_info.html:

<!DOCTYPE html>
{% extends "base.html" %}
<html>
<head>
    <title>{% block title %}templates/mainmenu.html{% endblock %}</title>
</head>
<body>

<div id="content">
    {% block content %}
    Mainmenu
    <a href="/statinfo/">stat info</a>
    {% endblock %}

</div>

</body>
</html>
Share:
12,220
JimJay
Author by

JimJay

Updated on June 04, 2022

Comments

  • JimJay
    JimJay almost 2 years

    I'm new to Django and trying to build a simple login system for my webpage using django.contrib.auth.views.login with Django 1.4. I have a base template containing the following login form which is then extended by other template pages on my website:

    <form method="post" action="/accounts/login/">
    {% csrf_token %}
    <p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="30" /></p>
    <p><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></p>
    <input type="submit" value="Log in" />
    <input type="hidden" name="next" value="{{ request.get_full_path }}" />
    </form>
    

    However when I try to login I get the following message:

    "Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect."

    Relevant snippets from urls.py:

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

    and settings.py:

    TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
    )
    
    .....
    
    INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    )
    .....
    MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    )
    

    Any suggestions?

    • dgel
      dgel about 12 years
      When you view the page source, is {% csrf_token %} being rendered as anything?
    • JimJay
      JimJay about 12 years
      No, nothing is being rendered for {% csrf_token %}
    • styts
      styts about 12 years
      can you try adding django.core.context_processors.csrf explicitly? or take a look with djnago-debug-toolbar if it's being activated.
    • JimJay
      JimJay about 12 years
      Ah ok, problem solved. I was using render_to_response and had to add csrf(request) manually to the context. Now I have switched to direct_to_template and the problem is fixed. Thanks!