Django 项目错误总结2

1. 关于csrf错误

CSRF(Cross-site request forgery)跨站请求伪造,也被称为“one click attack”或者session riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。

django中自带了防止CSRF攻击的手段,在form表单的action属性中,GET时不需要CSRF认证,而POST时需要。

一般而言,有两种解决办法:

① 启用csrf认证

• 在settings.py中启用中间件django.middleware.csrf.CsrfViewMiddleware

• 在views.py的render_to_response中,用RequestContext代替默认的Context,如下:

return render_to_response('a.html', data, context_instance=RequestContext(request, processors=[my_fun])) 

注:若想要重定向到一个action,则用HttpResponseRedirect

• 在模板文件中的 form 表单内添加 {% csrf_token %} 

② 关闭csrf认证

• 注释掉django.middleware.csrf.CsrfViewMiddleware即可

2. 后台传列表或者字典给js函数

这里容易遇到两个难题,一是中文会显示成unicode形式,二是引号会被转义,使得js函数出错

① 无论是字典还是列表,传给js都可以用json来处理:

import json
test_dict = {
    "weather": ["sun", "rainy", "windy"],
    "mood": ["happy", "sad"]
}

json_str = json.dumps(test_dict, ensure_ascii=False)


注:其中的ensure属性是为了解决中文编码问题

② 在django中有专门禁止转义的方式,只需在js函数用标签围住相关代码块即可

<script>
    function test_fun() {
        {% autoescape off %}
        var json_obj = {{ dict_json }}
        {% endautoescape %}
    }
</script>


发布了72 篇原创文章 · 获赞 34 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/shilei123456789666/article/details/79116458
今日推荐