Send file to django rest with ajax

In my project, I use ajax to send form data to back-end(django rest framework). but when I see the request.data, the image field is empty. but other fields are ok.

js(img is file input):

        $.ajax({
            method: 'POST',
            url: '/step5/send/',
            contentType: 'application/json',
            data: JSON.stringify({"date": date, "hour": time, "price": price, "document": img, "id": {{user.id}} }),
            success: function (res) {
                console.log(res);
            }, error: function (err) {
                console.log(err);
            }
        });

view:

@api_view(["POST"])
def step5_get_pay(request):
    date = request.data.get("date")
    hour = request.data.get("hour")
    price = request.data.get("price")
    document = request.data.get('document')
    id_ = request.data.get("id")

    user = User.objects.get(id=id_)
    Step5.objects.create(date=date, hour=hour, price=price, document=document, user=user)

    data = {
        "data": request.data,
    }
    return Response(data=data, status=200)

and data: {date: '1401-11-14', hour: '10:10:10', price: '500', document: {…}, id: 1}

Document is in request.data but I think It's must in request.FILES and in model that's save {} (empty)

enter image description here enter image description here

send a form with file input with ajax and django rest

Back to Top