Search code examples
pythonpython-3.xdjango

How can I send both file and json data in a single request in Django using Requests library on the client side?


I need to send json data and file to my api in django. In the client side i use requests and i will share that code below. I tried this code but it gave "django.http.request.RawPostDataException: You cannot access body after reading from request's data stream". Hope you can help.

client side:

import requests
my_json={
#some json data
}
file = {"file": open("sample.txt", "rb")}
response = requests.post(
    "http://127.0.0.1:8000/API/upload-file", data=my_json, files=file
)
print(response.text)

endpoint in views.py

def get_file(request):
    if request.method == "POST":
        uploaded_file = request.FILES["file"]
        json_data = json.loads(request.body)
        print(json_data)
        print(uploaded_file.filename)

Solution

  • After some researches i found out the solution. In client side sending json using data key of requests is essential. If you try to send it using json key you will get TypeError: can only concatenate str (not "NoneType") to str. The working code in server side is given below:

    from rest_framework.views import APIView
    
    class FileUploadView(APIView):
        def post(self, request, format=None):
            file = request.FILES.get("file")
            print("Uploaded file: " + file._get_name())
            json_data = {k: v for k, v in request.data.dict().items() if k != "file"}
            print(json_data)
    

    In my case I only needed a specific key pair from json so instead of converting i just simply used request.data.get("key_value").