Django 解决403问题

分两种情况,一种是正常提交,另一种是用ajax提交
正常提交的话,每个表单后面都要有{% csrf_token %}这个标签,在views.py里面相应的方法有两种书写方式:
方法一:

c = {}
c.update(csrf(request))
return render_to_response('news/add.html',c)

方法二:

return render_to_response('news/add.html', {},context_instance=RequestContext(request))

注意,对于方法二,一定要注意是在显示表单之前那个方法上面加上context_instance=RequestContext(request),就像下面这样:
对于登录窗口,显示登录窗口对应的views方法为:

def index(request):
    return render_to_response('account/login.html', {},context_instance=RequestContext(request))

注意是在这个方法的return函数里面加上context_instance=RequestContext(request),而不是在响应提交按钮的那个views方法里面加。这一点尤其需要注意。

   
如果是ajax提交的话,要在整个项目的首页,加上这一段代码:

//新加处理ajax提交表单的处理方式
jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie &&document.cookie != '') {
            var cookies= document.cookie.split(';');
            for (var i =0; i < cookies.length; i++) {
               var cookie = jQuery.trim(cookies[i]);
               // Does this cookie string begin with the name we want?
               if (cookie.substring(0, name.length + 1) == (name + '=')) {
                   cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                   break;
               }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or schemerelative or absolute
        var host = document.location.host;// host + port
        var protocol =document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relativeURLs to same origin
        return (url == origin ||url.slice(0, origin.length + 1) == origin + '/') ||
            (url ==sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or anyother URL that isn't scheme relative or absolute i.e relative.
           !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return(/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    if(!safeMethod(settings.type) && sameOrigin(settings.url)) {
       xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

views.py里面正常书写就行了,不需要做特殊处理:

return render_to_response('news/add.html')

关于csrf的处理一定要参照官方网站:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

你可能感兴趣的:(Django,Python)