Krish V
Krish V

Reputation: 546

django.utils.datastructures.MultiValueDictKeyError REST API post request

Getting django.utils.datastructures.MultiValueDictKeyError: 'email_id' while post request. Here's my code

views.py:

def post(self, request):
    video_file = self.request.data['media_file']
    user_email_id = self.request.data['email_id']

    file_storage = FileSystemStorage()
    saved_file_name = file_storage.save(str(uuid.uuid4()), video_file)

upload.py:

headers = {"Authorizarion": "auth/key"}
data = {"email_id": "[email protected]",
        "media_file": open(video.file_path, "rb")}
response = requests.post("/api/url", headers=headers, data=data)

When try to upload the file via Postman works fin as it takes care of Content-Type, but trying to upload in the backend makes it difficult to clear it.

Upvotes: 1

Views: 1176

Answers (1)

zwer
zwer

Reputation: 25799

It seems you're not passing the email_id - can you print its value in upload.py before you post?

To be on the safe side, provide a default value in your views.py:

video_file = self.request.data.get("media_file", None)
user_email_id = self.request.data.get("email_id", None)

Replace None with whatever you want as a default if a field is missing.

UPDATE: Of course, then you'll encounter the issue of uploading file contents the way you do. To upload the actual file you should use a files structure in your requests.post() call, e.g.:

headers = {"Authorizarion": "auth/key"}
data = {"email_id": "[email protected]"}
files = {"media_file": open(video.file_path, "rb")}
response = requests.post("/api/url", headers=headers, data=data, files=files)

Then on Django side you'll have to retrieve the contents as:

def post(self, request):
    video_file = request.FILES.get('media_file', None)
    user_email_id = request.POST.get('email_id', None)
    # you should probably validate video_file and user_email_id here
    file_storage = FileSystemStorage()
    saved_file_name = file_storage.save(str(uuid.uui`d4()), video_file)

Upvotes: 3

Related Questions