【问题标题】:django ajax call return 403 bad requestdjango ajax 调用返回 403 错误请求
【发布时间】:2016-08-17 04:24:22
【问题描述】:

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

并在 ajax 调用期间出现以下错误。

加载资源失败:服务器响应状态为 400 (BAD REQUEST)。

我知道这是因为 ajax 发布请求和 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'])

Ajax 调用 (home.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。 我从堆栈溢出中尝试了很多答案,但没有弄清楚问题出在哪里。

【问题讨论】:

  • 很难找出问题所在,因为您正在捕获所有异常并在您的视图中简单地返回403。打印所有例外情况并使用适当的详细信息更新问题。
  • 您明确告诉您的代码在发生任何异常时返回错误请求。通过这样做,您已经小心地隐藏了任何可以让您或我们实际调试问题的信息。删除那个裸露的尝试/除外。
  • @v1k45 :- 感谢您的评论。我不能在这里发布整个代码,所以请查看 repo:-github.com/kannan4k/django-carpool 当我访问 /new_trip 页面时,有一个按钮调用 home.js 中的 PostData() 方法,它尝试调用 /save_journey/ 这导致问题。
  • 我们不要求更多代码。只需删除 try/except 块并向我们展示您遇到的错误。
  • @v1k45:没有 Try/except 块,它给出了加载资源失败:服务器响应状态为 500(内部服务器错误)

标签: javascript jquery python ajax django


【解决方案1】:

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

这是一个示例,说明如何通过 csrftoken 将 Ajax 与 Django 一起使用:

您可以使用 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']

    # ...

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2017-10-07
    • 2011-10-11
    • 2016-05-14
    • 2022-07-31
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2011-02-07
    • 1970-01-01
    相关资源
    最近更新 更多