1

With Django 1.8, I do not want to have a cookie set on the homepage of my site when the users are not logged in. So I decorate my view with @csrf_exempt like

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def mainhome(request):

When I look at the query I can see the cookie still set, why ?

rodo@roz-desktop:~/(master)$ curl  -I http://127.0.0.1:8000/
HTTP/1.0 200 OK
Date: Sat, 13 Jun 2015 08:59:27 GMT
Server: WSGIServer/0.1 Python/2.7.8
Content-Type: text/html; charset=utf-8
Vary: Cookie
X-QueryInspect-Duplicate-SQL-Queries: 2
X-QueryInspect-Total-SQL-Time: 34 ms
X-QueryInspect-Total-Request-Time: 283 ms
X-QueryInspect-Num-SQL-Queries: 3
Set-Cookie:  csrftoken=sa5x0DyxgBamca0D84ZZnzl2WAL0evkv; expires=Sat, 11-Jun-2016 08:59:27 GMT; Max-Age=31449600; Path=/
Rodolphe
  • 848
  • 4
  • 15

2 Answers2

2

As @Daniel Roseman indicated, @csrf_exempt will not help you with that.

The middleware responsible for the session cookie is SessionMiddleware. You can read more about it in the Django Docs: How to use sessions. Unfortunately, there is no similar decorator in order to exempt some specific view.

So in order to customize the middleware's behaviour, you would need to inherit from SessionMiddleware. There is a nice answer on the matter on SO.

Community
  • 1
  • 1
Wtower
  • 18,848
  • 11
  • 103
  • 80
  • 1
    Thanks for this answer, it does exactly what I was looking for, the nice answer is really nice, shame that I hace not found it by myself. – Rodolphe Jun 13 '15 at 09:48
0

csrf_exempt controls whether or not CSRF is enforced on POST. It has nothing to do with whether or not the CSRF cookie is set; that is done by the CsrfViewMiddleware for all responses.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895