0

I am trying to send an image from python client to django server. But i failed to upload the file. The django code is

models.py

from django.db import models
class File(models.Model):
    file = models.FileField()
    def __str__(self):
        return self.file.name

Serializers.py

from rest_framework import serializers
from .models import File
class FileSerializer(serializers.ModelSerializer):
    class Meta:
        model = File
        fields = "__all__"

urls.py

from django.urls import path
from .views import *

urlpatterns = [
    path('', FileUploadView.as_view())
]

views.py

class FileUploadView(APIView):
    parser_class = (FileUploadParser,)

    def post(self, request, *args, **kwargs):

      file_serializer = FileSerializer(data=request.FILES)
      print(type(file_serializer))
      if file_serializer.is_valid():
          print('abc')
          file_serializer.save()
          return Response(file_serializer.data, status=status.HTTP_201_CREATED)
      else:
          return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

python client code is

import requests as req
name = {'name': open('im.jpeg', 'rb')}
resp = req.post('http://127.0.0.1:8000/upload', name)
print(resp)
print(resp.text)

the output is

{"file":["No file was submitted."]}

Kindly help me on this

mohan
  • 25
  • 4
  • it seems that the serializer (and the model) are looking for a parameter called "file" but, when you send the request you are doing it sending with the parameter called "name" – soloidx Mar 11 '20 at 03:42
  • I tried like that also files = { 'file': open('im.jpeg', 'rb'), } but no use – mohan Mar 11 '20 at 04:00
  • just learn about ```FileUploadParser``` https://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser. It doesn't work the way you expect here – Andrey Nelubin Mar 11 '20 at 05:12
  • 1
    send data as form object, hope this link will help you :- https://stackoverflow.com/questions/20759981/python-trying-to-post-form-using-requests, (or) you can send the data as form data in **postman**. – Saisiva A Mar 11 '20 at 06:47

0 Answers0