500(内部服务器错误)AJAX Django

时间:2018-03-01 08:39:54

标签: ajax django django-models

一切!你能帮帮我吗?我有一个小问题。当我单击按钮时,当我单击按钮时,应该创建一个新对象而不重新加载页面。创建对象只需要一个参数。

问题在于,当您单击创建对象时(新对象显示在管理面板中),但在控制台js中出现错误: Failed to load resource: the server responded with a status of 500 (Internal Server Error)

JS:

function initBuyButton(){
    $('.button-buy').click(function(e){
        e.preventDefault();
        var test = $(this);
        var smartphone_id = test.data("smartphone_id");
        var url = test.attr("action");

        basketUpdating(smartphone_id, url);
    });
}


function basketUpdating(smartphone_id, url){
    var data = {};
    var csrf_token = $('#form_buying_product [name="csrfmiddlewaretoken"]').val();

    data["csrfmiddlewaretoken"] = csrf_token;
    data.smartphone_id = smartphone_id;

    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        cache: true,
    });
}


$(document).ready(function(){
    initBuyButton();
});

查看:

def basket_adding(request):
    """Add new smartphone to basket."""
    data = request.POST
    smartphone_id = data.get('smartphone_id')
    SmartphoneInBasket.objects.create(smartphone_id=smartphone_id)

    return True

HTML:

<form id="form_buying_product" > {% csrf_token %}
  {% for sm in smartphones %}
 ...    
    <input type="submit" action="{% url 'basket_adding' %}" class="button-
     buy" data-smartphone_id = "{{ sm.id }}" value="Buy">
  {% endfor %}
</form>

3 个答案:

答案 0 :(得分:2)

如评论中所述,视图需要返回HttpResponse。如果你愿意,它可以是空的:

['b']

答案 1 :(得分:1)

您需要将__declspec(dllexport)作为标题添加。

csrf token

因为var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ url: url, type: 'POST', headers:{ "X-CSRFToken": csrftoken }, data: data, cache: true, }); 是您的权限被拒绝发送数据。

答案 2 :(得分:0)

我定义了以下辅助函数:

import json

def json_response(request, val, **kw):
    """Return a json or jsonp response.
    """
    if request.GET.get('callback'):
        return jsonp(request.GET['callback'], val, **kw)
    else:
        return jsonval(val, **kw)

def jsonval(val, **kw):
    """Serialize val to a json HTTP response.
    """
    data = dumps(val, **kw)
    resp = http.HttpResponse(data, content_type='application/json')
    resp['Content-Type'] = 'application/json; charset=UTF-8'
    return resp

def jsonp(callback, val, **kw):
    """Serialization with json callback.
    """
    data = callback + '(%s)' % json.dumps(val, **kw)

    return http.HttpResponse(
        data,
        content_type='application/javascript; charset=utf-8'
    )

使用那些定义的视图可以返回一个json对象(到你的ajax调用):

def basket_adding(request):
    """Add new smartphone to basket."""
    ...
    return json_response(request, True)

通常的做法是返回一个对象,所以也许:

    return json_response(request, {"status": True})
相关问题