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

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

问题描述

我最近升级到 Django 1.2.3,但我的上传表单已损坏.每当我尝试上传时,我都会收到CSRF 验证失败.请求中止".错误信息.

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.

阅读Django 的文档后 关于这个主题,它指出我需要在模板的 HTML <form> 中添加 {% csrf_token %} 模板标签.不幸的是,我的

是通过 JavaScript 生成的(特别是 ExtJs 在面板上的html"属性).

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).

长话短说,当我的 未包含在 Django 模板中时,如何将所需的 CSRF 令牌标记添加到我的 ?

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?

推荐答案

另一种选择是调整 the Django docs with Ext - 如果您有很多模板并且不想更改每个模板,则更可取.

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.

只需将以下代码段放入您的 overrides.js(或您放置全局修改的任何位置):

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);

(Ext已有cookie读取功能,无需复制)

这篇关于如何在 Javascript 生成的 HTML 表单中包含 Django 1.2 的 CSRF 令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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