Search code examples
pythondjangocsrfdjango-csrf

Django : CSRF token missing or incorrect


Django noob here ! I've tried basically every solution online and I still have the error (one Chrome) "CSRF token missing or incorrect" while Opera and Firefox return "CSRF cookie not set" instead...? Here are my files :

views.py

# views.py
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.template import RequestContext
from django.core.context_processors import csrf

def dashboard(request):
    state = "log in"
    if request.user.is_authenticated():
        return render_to_response('memberbrd.html')
    elif request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/')
            else: 
                error = "inactive"
        else:
            error = "wrong username or password"
        render_to_response('visitorbrd.html', {'errors': error}, context_instance = RequestContext(request)) # I've also tried without context_instance, without passing errors...
    else:
        return render_to_response('visitorbrd.html')

urls.py

#urls.py
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

from mission.views import *

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', dashboard),
)

visitorbrd.html

{% extends "base.html" %}
{% block content %}
    {% if state %}
        <p>{{ state }}</p>
    {% endif %}
    <form action="." method="POST">{% csrf_token %}
        <label for="username">User name:</label>
        <input type="text" name="username" value="" id="username">
        <label for="password">Password:</label>
        <input type="password" name="password" value="" id="password">
        <input type="submit" value="login" />
        <input type="hidden" name="next" value="{{ next|escape }}" />
    </form>
{% endblock %}

Thanks !


Solution

  • You're not using RequestContext for the final render_to_response which is responsible for actually showing the form.