1

I'm quite new to django and I just can't figure out a way to upload a simple html file to django using requests.post(). I tried the steps given in this https://blog.vivekshukla.xyz/uploading-file-using-api-django-rest-framework/ but I keep getting a status 400 when I give

import requests
file_ob = open("/root/Desktop/sampletext.html", "rb")
print(file_ob)
payload = {
    'remark1': 'hey',
    'remark2': 'hello',
    'File': file_ob
}
r = requests.post("http://127.0.0.1:8000/upload/files/", data=payload)
print(r.status_code)

models.py

class Files(models.Model):
    remark1 = models.CharField(max_length=20)
    remark2 = models.CharField(max_length=20)
    File = models.FileField(blank=False, null=False)

views.py

class FileView(APIView):
    parser_classes = (MultiPartParser, FormParser)
    def post(self, request, *args, **kwargs):
        file_serializer = FileSerializer(data=request.data)
        if file_serializer.is_valid():
            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)

    def get(self, request):
        files = Files.objects.all()
        file_serializer = FileSerializer(files, many=True)
        return Response(file_serializer.data, status=status.HTTP_200_OK)

serializers.py

class FileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Files
        fields = '__all__'

urls.py

urlpatterns=[
    path('admin/', admin.site.urls),
    path('upload/files/', FileView.as_view())
]

Here is the error I get from server:

Bad Request: /upload/files/
[12/May/2020 08:29:45] "POST /upload/files/ HTTP/1.1" 400 84

What am I doing wrong? Is there a better way to do this? I cant find any example online where requests.post() was used. It's Postman everywhere.

Roshan
  • 123
  • 1
  • 8
  • please add the output of `file_serializer.errors`. – Nalin Dobhal May 12 '20 at 08:20
  • general tip: avoid using variables starting with capital letters. Those are intended for class definitions. Instead of `File` you should stick to `file`. – anurag May 12 '20 at 08:40
  • Also, files need to be sent separately as mentioned here - https://stackoverflow.com/a/12385661/1320407 Update your `requests.post` as per the examples, and try again. – anurag May 12 '20 at 08:47
  • Tip noted. Just started to program 3 months ago, so not so well versed with the conventions. Yep passing the files separately did the trick. Thanks so much! – Roshan May 12 '20 at 11:52

1 Answers1

4

Try this,

import requests
file_ob = {'uploaded_file': open('/root/Desktop/sampletext.html', 'rb')
print(file_ob)
payload = {
    'remark1': 'hey',
    'remark2': 'hello',
}
r = requests.post("http://127.0.0.1:8000/upload/files/", files=file_ob, data=payload)

print(r.status_code)
Md. Tanvir Raihan
  • 4,075
  • 9
  • 37
  • 70