简体   繁体   English

Python - 使用csrf保护进行渲染

[英]Python - render with csrf protection

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. 我已经阅读了几篇关于Django中csrf保护的帖子,包括Django的文档 ,但我仍然对如何正确使用它感到困惑。

The clearest part is the HTML one, but the Python's one is kinda confusing. 最清楚的部分是HTML,但Python的有点令人困惑。

HTML HTML

{% csrf_token %} inside the form 表单内的{% csrf_token %}

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() ? 那么,如何在return render()包含此csrf保护? 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) ). 或者我应该在Python文档示例中包含creturn render_to_response("a_template.html", c) )。 Or, if it's correct, is it included in the request var? 或者,如果它是正确的,它是否包含在request变量中?


And, when not needing to use csrf because I don't have any form. 并且,当不需要使用csrf时,因为我没有任何形式。 Would this be the right form to return values to a template? 这是将值返回到模板的正确形式吗?

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

The point of using the render shortcut is that it then runs all the context processors automatically. 使用render快捷方式的关键是它会自动运行所有上下文处理器。 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. 并且有一个内置的上下文处理器,已经为您添加了CSRF令牌。 So, if you use render , there is nothing more to do other than to output the token in the template. 因此,如果使用render ,除了在模板中输出令牌之外别无其他功能。

As far as I remember Django has its own middleware for the csrf protection that handles everthing transparently for you. 据我所知,Django有自己的csrf保护中间件,可以为您透明地处理外包。 Just include the {% csrf_token %} inside you forms. 只需在表单中包含{% csrf_token %} CSRF token is mandatory for POST requests (except you use the @csrf_exempt decorator). CSR请求对于POST请求是必需的(除了您使用@csrf_exempt装饰器)。 So a form would be: 所以一个表格将是:

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

Hope this helps. 希望这可以帮助。

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. 只要您在设置文件中的MIDDLEWARE_CLASSES变量中列出了“django.middleware.csrf.CsrfViewMiddleware”,您就应该在模板中使用{%csrf_token%}。

There's a lot more useful info in the docs: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ 在文档中有更多有用的信息: https//docs.djangoproject.com/en/dev/ref/contrib/csrf/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM