无法使用postgresql在django中发出ajax请求

时间:2017-10-24 09:19:59

标签: jquery ajax django postgresql

所以我开发了一个django应用程序,我正在尝试将一些东西发布到Postgresql,我知道在对视图发出的ajax请求期间需要CSRF令牌,这是我的csrf.js ,我已经包含在我的标题模板中

  // using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

这是我在模板中提出的ajax请求

$.ajax({type: 'POST',
            url: '/sample/saveData/',                            // some data url
            data: {param: workHours.length, param1: $(getDayName[i]).text(),param2: bla,param3: bla1,param4: bla2}, 
                            // some params  
            success: function (response) {                  // callback
                if (response.result === 'OK') {
                    if (response.data && typeof(response.data) === 'object') {
                        // do something with the successful response.data
                        // e.g. response.data can be a JSON object
                    }
                } else {
                    window.alert(response.result);
                }
            }
           });

这是我的观点,我希望这有帮助

def saveData(request):
    if request.is_ajax():
         # extract your params (also, remember to validate them)

        param = request.POST.get('param', None)
        param1 = request.POST.get('param1', None)
        param2 = request.POST.get('param2', None)
        param3 = request.POST.get('param3', None)
        param4 = request.POST.get('param4', None)
        stringData=datetime.datetime.now().strftime('%H:%M:%S')+" ("+param1+")"
        #another_param = request.POST.get('another param', None)
        #return HttpResponse(param, mimetype)
        p = Post(user="John",weekOfthemonth=param2 ,didAttend='Yes',date=stringData,numofHours=param,logIn=param3,logOut=param4)
    p.save()
    return HttpResponseBadRequest()

2 个答案:

答案 0 :(得分:0)

如果你想使用csrf_exempt你不必使用jquery cookie函数: 转到save_data视图并将其添加到其中

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def save_data(request):
    [...] your code

答案 1 :(得分:0)

CSRF令牌存在于django呈现的模板中。因此,您只需要在jquery帖子中传递它。

我相信您可以简化大部分代码,也不需要csrf.js。更改$ .ajax调用的数据参数以包含csrf标记。

        data: {param: workHours.length, 
               param1: $(getDayName[i]).text(),
               param2: bla,
               param3: bla1,
               param4: bla2,
               csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value},