如何将Django 1.2的CSRF令牌包含在JavaScript生成的HTML表单中? [英] How do I include Django 1.2's CSRF token in a Javascript-generated HTML form?
问题描述
阅读 Django的文档,它指出我需要在HTML < form>
< form>
是通过JavaScript(特别是Panel上的ExtJs的html属性)生成的。 长篇小说,如果我的< form> $ c,那么如何将所需的CSRF令牌标签添加到我的
< form>
$ c>不包含在Django模板中?
另一个选择是调整基于cookie / Django文档与Ext - 如果您有很多模板,而不想更改每一个模板,则最好使用。
只需将以下代码片段放在overrides.js中(或者将全局修改):
Ext.Ajax.on('beforerequest',function(conn,options){
if( !(/ ^ http:。* /。test(options.url)|| /^https:.*/.test(options.url))){
if(typeof(options.headers)== undefined){
options.headers = {'X-CSRFToken':Ext.util.Cookies.get('csrftoken')};
} else {
options.headers.extend({'X-CSRFToken':Ext.util.Cookies.get('csrftoken')});
}
}
},这个);
(编辑:Ext已经有cookie读取功能,不需要复制它) em>
I recently upgraded to Django 1.2.3 and my upload forms are now broken. Whenever I attempt to upload, I receive a "CSRF verification failed. Request aborted." error message.
After reading Django's documentation on this subject, it states that I need to add the {% csrf_token %} template tag within the HTML <form>
in my template. Unfortunately, my <form>
is generated via JavaScript (specifically, ExtJs's "html" property on a Panel).
Long story short, how do I add the required CSRF token tag to my <form>
when my <form>
is not included in a Django template?
Another option would be to adapt the cookie/header based solution shown in the Django docs with Ext - preferable if you have a lot of templates and don't want to change every single one.
Just drop the following snippet in your overrides.js (or wherever you put global modifications):
Ext.Ajax.on('beforerequest', function (conn, options) {
if (!(/^http:.*/.test(options.url) || /^https:.*/.test(options.url))) {
if (typeof(options.headers) == "undefined") {
options.headers = {'X-CSRFToken': Ext.util.Cookies.get('csrftoken')};
} else {
options.headers.extend({'X-CSRFToken': Ext.util.Cookies.get('csrftoken')});
}
}
}, this);
(edit: Ext already has cookie reading function, no need to duplicate it)
这篇关于如何将Django 1.2的CSRF令牌包含在JavaScript生成的HTML表单中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!