gpt4 book ai didi

javascript - 如何在 Django 中向基于类的 View 发出 POST 请求

转载 作者:行者123 更新时间:2023-11-28 14:57:12 25 4
gpt4 key购买 nike

我在 Django 上创建了不同的基于类的 View 。在 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)
}
});
});
});

我从网上得到了一些代码,但我真的不知道如何使用它,因为他们在没有基于类的 View 的情况下使用它。

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

最佳答案

基于类的 View 的 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'})

关于javascript - 如何在 Django 中向基于类的 View 发出 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42447679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com