Python - csrf protected render

I read several posts about csrf protection in Django, including the Django documentation , but I'm still quite confused about how to use it correctly.

The brightest part is the HTML, but Python is somewhat confused.

HTML

{% csrf_token %} inside the form

Python

 c = {} c.update(csrf(request)) 

You need this in every form when displaying and requesting information, right?


Then how to enable this csrf protection in return render() ? Is it correct?

return render(request,'index.html',{'var':var_value})

or include c somewhere, as in the Python documentation sample example ( return render_to_response("a_template.html", c) ). Or, if it is correct, is it included in request var?


And, when you do not need to use csrf, because I do not have any form. Will this be the correct form to return values ​​to the template?

return render(request,'index.html',{'var':var_value})

+4
source share
3 answers

The point of using the render shortcut is that it automatically starts all context processors. Context processors are useful functions that add various things to a template context each time a template is rendered. And there is a built-in context processor that already adds the CSRF token for you. So, if you use render , you don’t have to do anything else but print the token into the template.

+3
source

As far as I remember, Django has its own csrf security middleware that provides transparency for you. Just include {% csrf_token %} inside the forms. The CSRF token is required for POST requests (other than using the @csrf_exempt decorator). Thus, the form would be as follows:

 <form action="." method="post"> {% csrf_token %} your input fields and submit button... </form> 

Hope this helps.

0
source

As long as you have the parameter "django.middleware.csrf.CsrfViewMiddleware" specified in your MIDDLEWARE_CLASSES variable in the settings file, you should just have {% csrf_token%} in your templates.

The docs have much more useful information: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

0
source

Source: https://habr.com/ru/post/1489129/


All Articles