如何在django中基于类视图的put请求中访问数据表单

时间:2017-07-05 13:43:19

标签: jquery python ajax django

我目前在访问存储在数据表单中的数据时遇到问题。我通过ajax传递它,并通过views.py中的put方法接收它。问题是我只知道如何通过request.POST [“item_name”]和文件request.FILES [“photo”]访问它。但显然这在put请求中不起作用。有人可以帮忙吗?

的jQuery

const form = new FormData();
const name = $('#edit-product-name-input-' + productID).val();
const quantity = $('#edit-product-quantity-input-' + productID).val();
const description = $('#edit-product-description-input-' + productID).val();
const price = $('#edit-product-price-input-' + productID).val();
const photo = $('#edit-product-photo-' + productID);

if (extractPhoto(photo)) {
    form.append('photo', extractPhoto(photo));
}
form.append('name', name);
form.append('price', price);
form.append('description', description);
form.append('quantity', quantity);
form.append('product_id', productID);

attachCSRF();
$.ajax({
    url: window.location.pathname + "products/",
    method: "PUT",
    data: form,
    contentType: false,
    processData: false,
    success: function (data) {
        alert(data["product"] + " edited");
        location.reload();
    },
    error: function (data) {
        if (data.responseJSON) {
            displayErrors(data.responseJSON);
        }
    }

views.py

@staticmethod
def put(request, stall_id):
    dict = {
        "product_name": request.body('name'),
        "description": request.body('description'),
        "price": request.body('price'),
        "quantity": request.body('quantity')
    }
    errors = handle_errors(dict)
    print(errors)

    if not errors:
        product = Product.objects.get(id=request.POST.get("product_id"))
        product.name = dict["product_name"]
        product.description = dict["description"]
        product.price = dict["price"]
        product.quantity = dict["quantity"]
        if 'photo' in request.FILES:
            product.photo = request.FILES.get('photo')
        product.save()


        data = {
            "product": product.name
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    return HttpResponse(
        json.dumps(errors),
        content_type="application/json",
        status=400
    )

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,QueryDict(request.body)对我不起作用。

最后我要做的是:

from django.http.multipartparser import MultiPartParser
put_data = MultiPartParser(request.META, request, request.upload_handlers).parse() # it will return a tuple object
put = put_data[0] # it will give you the QueryDict object with your form data.

答案 1 :(得分:0)

看起来,当通过x-www-form-urlencoded发送数据时,它以request.body字节到达。

**请勿在我刚刚用于测试目的的代码中使用csrf_exempt。**

以下内容适用于我:

from django.http import QueryDict


class Some(View):
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, *kwargs)

    def put(self, request, *args, **kwargs):
        data = QueryDict(request.body)
        print(data)
        return HttpResponse("Worked!")

data变量是dict,因此您可以在汇总内执行此操作:

form = {
    "product_name": data.get('name'),
    "description": data.get('description'),
    "price": data.get('price'),
    "quantity": data.get('quantity')
}