【问题标题】:How can i perform PUT request using ajax and jquery in Django?如何在 Django 中使用 ajax 和 jquery 执行 PUT 请求?
【发布时间】:2020-02-28 13:37:50
【问题描述】:

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

【问题讨论】:

  • 我正在使用 POST 来从表单中获取数据。一旦我得到我想要使用 PUT 的数据。
  • 需要更具体地说明您遇到的具体问题
  • 我不知道如何实现 PUT 请求
  • 就前端而言 ($.ajax),您的操作方式与 POST 相同,但将 method 更改为 'PUT'
  • 我试过了,但是我得到了这个:“403(禁止)”

标签: javascript jquery django ajax django-models


【解决方案1】:

那个 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's CBV

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 2020-01-04
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多