Python - render with csrf protection

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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

The clearest part is the HTML one, but the Python's one is kinda confusing.

HTML

{% csrf_token %} inside the form

Python

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

You need it in every form when displaying and requesting the information, don't you?


Then, how do you include this csrf protection in the return render()? Is this correct?

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

or should I include the c somewhere like in the Python documentation example (return render_to_response("a_template.html", c)). Or, if it's correct, is it included in the request var?


And, when not needing to use csrf because I don't have any form. Would this be the right form to return values to a template?

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

回答1:

The point of using the render shortcut is that it then runs all the context processors automatically. Context processors are useful little functions that add various things to the template context every 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, there is nothing more to do other than to output the token in the template.



回答2:

As far as I remember Django has its own middleware for the csrf protection that handles everthing transparently for you. Just include the {% csrf_token %} inside you forms. CSRF token is mandatory for POST requests (except you use the @csrf_exempt decorator). So a form would be:

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

Hope this helps.



回答3:

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

There's a lot more useful info in the docs: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!