【问题标题】:How to make POST requests to class-based Views in Django如何在 Django 中向基于类的视图发出 POST 请求
【发布时间】:2017-02-24 20:26:49
【问题描述】:

我在 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 方法?

【问题讨论】:

    标签: javascript python django


    【解决方案1】:

    基于类的视图的dispatch 方法确定调用哪个函数,到目前为止,您已经编写了一个get 函数,但没有post 函数,所以只需将逻辑移到一个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'})
    

    【讨论】:

    • 这个,以及应该处理请求的类是另一个的事实,起作用了。谢谢!
    猜你喜欢
    • 2019-10-30
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 2021-10-05
    • 2015-12-02
    • 2016-09-29
    相关资源
    最近更新 更多