2017-02-24 143 views
0

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

不允许的方法(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) 
     } 
    }); 
    }); 
}); 

我得到了一些来自Web的代码发送reques,但我真的不知道如何使用它,因为他们没有使用基于类的视图。

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

回答

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'}) 
+1

这个,以及应该处理请求的类是另一个的事实。谢谢! –

相关问题