如何在Django中对基于类的视图发出POST请求

时间:2017-02-24 20:26:50

标签: javascript python django

我在Django上创建了不同的基于类的视图。在我创建的HTML上,一些表单使用AJAX发出请求。我的问题是它给了我

不允许的方法(POST)

我不知道我是否正在做这件事,或者我是否需要修改一些东西才能发挥作用。

我的view.py是这样的

class Landing(View):
    def get(self,request):
        if request.method == 'POST':
            if request.is_ajax():
                data = {"lat":20.586, "lon":-89.530}
                print request.POST.get('value')
                return JsonResponse(data)
    return render(request,'landing.html',{'foo':'bar'})

我从Javascript发送请求

$(document).ready(function() {
  $('#productos').on('change', function(e) {
     //Call the POST
     e.preventDefault();
     var csrftoken = getCookie('csrftoken');
     var value = $('#productos').val();

     $.ajax({
        url: window.location.href,
        type: "POST",
        data: {
            csrfmiddlewaretoken : csrftoken,
            value : value
        },
        success : function(json) {
            console.log(json);
            drop(json);
        },
        error : function(xhr,errmsg,err){
            console.log(xhr.status+": "+xhr.responseText)
        }
     });
  });
});

我从网上获得了一些代码,但我真的不知道如何使用它,因为他们使用它而没有基于类的视图。

那么,我的代码需要什么才能接受POST方法?

1 个答案:

答案 0 :(得分:2)

基于类的视图的dispatch方法确定调用哪个函数,到目前为止,您已编写了get函数,但没有编写post函数,因此只需将逻辑移入发布功能。

class Landing(View):
    def post(self,request):
        if request.is_ajax():
            data = {"lat":20.586, "lon":-89.530}
            print request.POST.get('value')
            return JsonResponse(data)

    def get(self, request):
         return render(request,'landing.html',{'foo':'bar'})