0

我一直在努力尝试使用 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
        })
4

1 回答 1

0

403 是由 CSRF 异常引起的。

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

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

我强烈建议您查看Django 的 CBV

于 2019-11-02T17:22:30.887 回答