Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is @csrf_exempt

What is @csrf_exempt, and why should we use this in our views.py? Also, are there any alternatives to it?

like image 605
Sharif Avatar asked Aug 06 '18 14:08

Sharif


People also ask

What does CSRF exempt do?

Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.

What is Csrf_protect?

The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries.

Why we use CSRF token in Django?

Django features a percent csrf token percent tag that is used to prevent malicious attacks. When generating the page on the server, it generates a token and ensures that any requests coming back in are cross-checked against this token. The token is not included in the incoming requests; thus they are not executed.

What is the use of CSRF exempt in Django?

If you add @csrf_exempt to the top of your view, then you are basically telling the view that it doesn't need the token. This is a security exemption that you should take seriously. Save this answer. Show activity on this post.


2 Answers

Normally when you make a request via a form you want the form being submitted to your view to originate from your website and not come from some other domain. To ensure that this happens, you can put a csrf token in your form for your view to recognize. If you add @csrf_exempt to the top of your view, then you are basically telling the view that it doesn't need the token. This is a security exemption that you should take seriously.

like image 156
Matt Cremeens Avatar answered Oct 05 '22 03:10

Matt Cremeens


The decorator marks a view as being exempt from the protection ensured by the middleware. Example:

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')
like image 41
Philip Mutua Avatar answered Oct 05 '22 02:10

Philip Mutua