如何将Django 1.2的CSRF令牌包含在JavaScript生成的HTML表单中? [英] How do I include Django 1.2's CSRF token in a Javascript-generated HTML form?

查看:94
本文介绍了如何将Django 1.2的CSRF令牌包含在JavaScript生成的HTML表单中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近升级到Django 1.2.3,我的上传表格现在已经坏了。每当我尝试上传,我收到CSRF验证失败,请求中止。错误消息。



阅读 Django的文档,它指出我需要在HTML < form>

中添加{%csrf_token%}模板标签, code>在我的模板。不幸的是,我的< form> 是通过JavaScript(特别是Panel上的ExtJs的html属性)生成的。



长篇小说,如果我的< form> < 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屋!

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