如何将django csrf令牌直接嵌入到HTML中? [英] How can I embed django csrf token straight into HTML?

查看:262
本文介绍了如何将django csrf令牌直接嵌入到HTML中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django应用程序中,我将数据库中的HTML字符串存储在用户的主页上,作为消息。这些消息中的一些包含表单,但不是用模板语言编写,我无法插入csrf标记(从而打破了应用程序)。



有没有办法从我正在编辑的python文件中直接插入这个标记?我正在寻找一些符合以下条件的东西:

  csrf_token = django.csrf.generate()
message = 请按下按钮:< form>< input type ='hidden'name ='csrf_token'value ='%s'>< input type ='submit'value ='press here'>< /形式>中%(csrf_token)

可以在类似情况下工作的任何其他解决方案将是巨大的。
感谢



编辑:
实际上这不会工作,因为每个会话的令牌都不同,所以存储它在db中并不是很有用。有没有办法在视图内动态加载令牌?

解决方案

调用 django.middleware.csrf .get_token(request)获取CSRF令牌。


within my django app I am storing strings of html in the db that will then be displayed on the users' home pages as "messages". Some of these messages contain forms, but not being written in the template language, I am not able to insert the csrf token (thus breaking the app).

Is there a way to insert this token directly from within the python files i'm editing? i'm looking for something along the lines of:

csrf_token = django.csrf.generate()
message = "press the button please: <form><input type='hidden' name='csrf_token' value='%s'><input type='submit' value='press here'></form>" % (csrf_token)

any other solution that would work in a similar scenario would be great. Thanks

Edit: Actually that's not going to work because the token is different for each session, so storing it in the db is not very useful. is there a way to dynamically load the token within the view?

解决方案

Call django.middleware.csrf.get_token(request) to get the CSRF token.

这篇关于如何将django csrf令牌直接嵌入到HTML中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆