Django Ajax 调用返回 403 错误请求

django ajax call return 403 bad request

本文关键字:错误 请求 返回 Ajax 调用 Django      更新时间:2023-09-26

我正在尝试编译项目 https://github.com/kannan4k/django-carpool有关此问题,请参阅此项目存储库。

并最终在 AJAX 调用期间出现以下错误。

无法加载资源:服务器以状态 400(错误请求)响应。

我知道这是因为ajax post request和CSRF令牌。以下是我的设置。1. 禁用"django.middleware.csrf.CsrfViewMiddleware"2.在new_trip页面中,我有一个按钮(Postdata),因此此按钮发送ajax请求。

我的观点:-

@login_required
def save_journey(request):
    if request.is_ajax() and request.method == "POST":
        try:
            res = json.loads(request.body)
            cords = res['cords']
            cords = [[x['d'], x['e']] for x in cords]
            distance = res['distance']
            start_place = res['start']
            end_place = res['end']
            clusters = clusterize_latlngs(cords, distance)
            time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
            Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
                                start_place=start_place, end_place=end_place)
            return HttpResponse()
        except:
            return HttpResponseBadRequest()
    else:
        return HttpResponseNotAllowed(['POST'])

阿贾克斯电话(主页.js)

function postData() {
    radius = 0;
    var url = "/save_journey/";
    var dataType = 'json';
    if (type == 'r') {
        radius = $('#radius').val();
        url = "/get_results/";
        dataType = 'html';
    }
    var data = JSON.stringify({
        cords: myroute,
        time: document.getElementById('dateStart').value,
        start: document.getElementById('startPlace').innerHTML,
        end: document.getElementById('endPlace').innerHTML,
        radius: radius,
        distance: distance
    });
    $.ajax({
        type: "POST",
        url: url,
        dataType: dataType,
        data: data,
        success: function (data) {
            if (type == 'r') {
                window.location.href = "/search_results/";
            }
            else {
                window.location.href = '/trip_success/';
            }
        },
        error: function () {
            console.log('Error getting options list...')
        }
    });
    console.log(data);
}

此代码无法调用/save_journey/URL。我从堆栈溢出中尝试了许多答案,但没有弄清楚问题是什么。

除非你绝对确定自己在做什么,否则你永远不应该禁用csrftoken。它是 Django 中实现的安全功能的重要组成部分。

下面是一个如何将 Ajax 与 Djan csrftoken go 一起使用的示例:

您可以使用 Ajax Post 将JSON发送到 Django,然后将参数作为dict()处理。下面是一个示例:

在浏览器中(JQuery/JavaScript):

    function newModule() {
        var my_data = $("#my_element").val(); // Whatever value you want to be sent.
        $.ajax({
            url: "{% url 'modules' %}",       // Handler as defined in Django URLs. 
            type: "POST",                     // Method.
            dataType: "json",                 // Format as JSON (Default).
            data: {
                path: my_data,                // Dictionary key (JSON). 
                csrfmiddlewaretoken: 
                         '{{ csrf_token }}'   // Unique key.
            },
            success: function (json) {
                // On success do this.
            },
            error: function (xhr, errmsg, err) {
                // On failure do this. 
            }
        });

在服务器引擎(Python)中:

def handle(request):
    # Post request containing the key.  
    if request.method == 'POST' and 'my_data' in request.POST.keys():
        # Retrieving the value.
        my_data = request.POST['my_data']
    # ...

希望这有帮助。