Sunday 28 July 2013

django's 'post' metod: about csrf protection

The CSRF middleware in django provides easy-to-use protection against Cross Site Request Forgeries. it is also regards as default way of execution

how it works

1, the middle ware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes.

2, On server side the csrf is csrf_token like:
<form action="." method="post">{% csrf_token %}
You may need manually update the csrf by:
    
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
    
def my_view(request):
    c = {}
    c.update(csrf(request))
    return render_to_response("a_template.html", c)
 
3,if you already added the the csrf middleware and you do not want to apply it, you should added
@csrf_exempt
 
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world') 
it is very import to added @csrf_exempt if you want to use ajax in django framework.