POST method always return 403 Forbidden

goFrendiAsgard picture goFrendiAsgard · May 19, 2012 · Viewed 52.9k times · Source

I have read Django - CSRF verification failed and several questions (and answers) related to django and POST method. One of the best-but-not-working-for-me answer is https://stackoverflow.com/a/4707639/755319

All of the approved answers suggest at least 3 things:

  1. Use RequestContext as the third parameter of render_to_response_call
  2. Add {% csrf_token %} in every form with POST method
  3. Check the MIDDLEWARE_CLASSES in settings.py

I've done exactly as suggested, but the error still appeared. I use django 1.3.1 (from ubuntu 12.04 repository) and python 2.7 (default from ubuntu)

This is my View:

# Create your views here.
from django.template import RequestContext
from django.http import HttpResponse
from django.shortcuts import render_to_response
from models import BookModel

def index(request):
    return HttpResponse('Welcome to the library')

def search_form(request):
    return render_to_response('library/search_form.html')

def search(request):
    if request.method=='POST':
        if 'q' in request.POST:
            q=request.POST['q']
            bookModel = BookModel.objects.filter(title__icontains=q)
            result = {'books' : bookModel,}
            return render_to_response('library/search.html', result, context_instance=RequestContext(request))
        else:
            return search_form(request)
    else:
        return search_form(request)

and this is my template (search_form.html):

{% extends "base.html" %}
{% block content %}
<form action="/library/search/" method="post">
    {% csrf_token %} 
    <input type="text" name="q">
    <input type="submit" value="Search">
</form>
{% endblock %}

I've restarted the server, but the 403 forbidden error is still there, telling that CSRF verification failed.

I've 2 questions:

  1. How to fix this error?
  2. Why is it so hard to make a "POST" in django, I mean is there any specific reason to make it so verbose (I come from PHP, and never found such a problem before)?

Answer

laycat picture laycat · Jun 28, 2013

I maybe wrong however I found the above solutions rather complex.

what worked for me was simply including my csrf token into my post request.

$.ajax({
    type: "POST",
    url: "/reports/",
    data: { csrfmiddlewaretoken: "{{ csrf_token }}",   // < here 
            state:"inactive" 
          },
    success: function() {
        alert("pocohuntus")
        console.log("prototype")
    }
})