如何在Django中使用ajax和jquery执行PUT请求



我已经挣扎了几个小时,试图使用PUT请求更新django中的数据库。我正在从表单中收集数据,我想根据用户键入的文本更新数据库条目。我特别需要使用PUT请求方法,但我不知道如何做到。任何帮助都将非常感谢

在这里,我从表单中获取数据:

$("#modify-btn").click(function(){
console.log('modify pressed')
$.ajax({
url : "{% url 'modify item' %} ",
method : "POST",
data: $("#detailsForm").serializeArray(),
success : function (data) {
console.log(data.id,data.name,data.brand,data.model)
/////
$.ajax({ /// this is where i need to use the PUT request
url : 
})

///
}
})
})

这是我的views.py文件:

from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.template import loader
from phonemodels.models import Phone
def index(request):
return render(request,'phonemodels/index.html',{
'phones' : Phone.objects.all(),
})
def items_json(request):
return JsonResponse({
'phones' : list(Phone.objects.values())
})
def new_item(request):
phone_name = request.POST['Brand']
phone_model = request.POST['Model']
phone_price = request.POST['Price']
phone = Phone (brandName=phone_name,phoneModel=phone_model,phonePrice=phone_price)
phone.save()
return JsonResponse({
'id' : phone.id,
'brand': phone.brandName,
'model' : phone.phoneModel,
'price' : phone.phonePrice
})
def modify_item(request):
phone_name = request.POST['BrandModify']
phone_model = request.POST['ModelModify']
phone_price = request.POST['PriceModify']
phone = Phone.objects.get(brandName=phone_name,phoneModel=phone_model,phonePrice=phone_price)
phone.id
return JsonResponse({
'id' : phone.id,
'name': phone_name,
'brand': phone_model,
'model' : phone_price
})

403是由CSRF异常引起的。

尽管如此,如果您想发出PUT请求,它应该相当简单:

  1. 您正在使用方法PUT发送$.ajax请求
$.ajax({
url: '',
method: 'PUT'
})
  1. 您在基于函数的视图中处理PUT请求,但必须确保它用csrf_exempt装饰器包装:
path('your-url/', csrf_exempt(modify_item), name='modify-item-url')

我强烈建议你调查Django的CBV

最新更新