[英]How to make POST requests to class-based Views in 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方法?
基于类的视图的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'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.