3

I am curious: I know there are 2 ways of csrf protection in Django: {% csrf_token %} in templates and @csrf_protect in views.

So, question is: are they interchangeable? I mean I can use for example only @csrf_protect i my views without {% csrf_token %} tag in my templates and effect will be the same?

I'm asking that because I use mako in recent Django project and there is no such tag as {% csrf_token %}...

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Vitalii Ponomar
  • 10,686
  • 20
  • 60
  • 88
  • 1. `{% csrf_token %}` must be there in templates 2. view should either be protected by `@csrf_protect` or by `CSRF middleware`. If you are using other template engine or AJAX, you need to provide csrf token in the template context. Read how : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#other-template-engines – user Mar 21 '14 at 11:32

1 Answers1

3

You need both. {% csrf_token %} adds hidden fields that is included in POST requests. While @csrf_protect adds a context variable that is used by {% csrf_token %}.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    But documentation says: 1) Alternatively, you can use the decorator csrf_protect() on particular views you want to protect (see below). 2) Rather than adding CsrfViewMiddleware as a blanket protection, you can use the csrf_protect decorator, which has exactly the same functionality, on particular views that need the protection. It must be used both on views that insert the CSRF token in the output, and on those that accept the POST form data. – Vitalii Ponomar Nov 13 '11 at 08:10
  • 1
    @VitaliPonomar You always need the `{% csrf_token %}` inside your form, and the view has to add the context variable needed. If the context variable is added through the decorator, middleware, or manually added doesn't matter, just that it comes as a pair. – Some programmer dude Nov 13 '11 at 08:18