HttpResponse对象。如何正确使用?

时间:2018-03-12 06:49:55

标签: ajax django django-views httpresponse

所有。我是Django的最新版本,我有一个问题。我想学习我需要的东西返回ajax get / post请求。我有例子,但我知道这不好。你能解释一下我的回答吗?何时,何以及为何?我没有找到任何有关它的信息。

当我点击按钮时,对象将从数据库中删除。

这是我的ajax请求:

function removeProduct(){
    $('.btn-remove').click(function(e){
        e.preventDefault();
        var data = {};
        data["csrfmiddlewaretoken"] = $('#quantity_goods [name="csrfmiddlewaretoken"]').val();
        var product = $(this);
        data.product_id = product.data("product_id");
        var url = product.attr("action");

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

这是我的观点:

def remove_product(request):
    """Remove product from basket."""
    data = request.POST
    product_id = data.get('product_id')

    product = ProductInOrder.objects.filter(id=product_id)
    product.delete()

    return HttpResponse()

1 个答案:

答案 0 :(得分:0)

这是我的工作方式

var username_ok = false;
var email_ok = false;

/*CSRF Code */

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative 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 relative URLs 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 any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}

/* End CSRF Code */

$(function() {

    $('#username, #email').focus(function() {
        var value = $(this).val();

        if (value == 'required') {
            $(this).val(null);
        }
    });

    $('#username').change(function() {
        var username = $(this).val();
        var data = {'username': username};

        var csrftoken = $.cookie('csrftoken');

        $.ajax({
            url: "/ajax_username",
            type: "POST",
            dataType: 'json',
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                    // Send the token to same-origin, relative URLs only.
                    // Send the token only if the method warrants CSRF protection
                    // Using the CSRFToken value acquired earlier
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }

            },
            data: JSON.stringify(data),
            success: function(response){
                if (response['status'] == 'ok') {
                    if (response['exists'] == true) {
                        $('.username-exists').removeClass('hidden');
                        username_ok = false;
                    } else {
                        $('.username-exists').addClass('hidden');
                        username_ok = true;
                    }
                }   
            }


            });

        /* End Ajax Call */
    });

后端

import json

def username_ajax(request):
    response = {'status': None}

    if request.method == 'POST':
        data = json.loads(request.body)
        username = data['username']

        response['exists'] = bool( User.objects.filter(username=username))
        response['status'] = 'ok'
    else:
        response['error'] = 'no post data found'

    return HttpResponse(
            json.dumps(response),
            content_type="application/json"
        )

希望有所帮助