Django Rest Framework File Upload

Django Rest Framework File Upload

Use the FileUploadParser, it's all in the request.
Use a put method instead, you'll find an example in the docs :)

class FileUploadView(views.APIView):
parser_classes = (FileUploadParser,)

def put(self, request, filename, format=None):
file_obj = request.FILES['file']
# do some stuff with uploaded file
return Response(status=204)

How to upload file to Django rest framework API using Axios and react hook form?

I have found the solution.

Turns out I have to add a header 'Content-Type': 'multipart/form-data' to the Axios Request.

I am posting the updated code below:

Axios Call

const onSubmit = data => {
const payload = {
blogtitle: data.title,
blogcontent: data.details,
blogimg: data.image['0'],
}
console.log(payload);
myAxios.post('/api/post/', payload, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err.response.data);
})
}

Django Rest Framework Patch Request with Image Upload

You need to use .save() for your serializer instead like this:

if serializer.is_valid():
try:
serializer.save()
except ValueError:
return Response({"detail": "Serializer is not valid"}, status=400)
return Response({"detail": "Updated."})
else:
return Response(serializer.errors)

This is also going to return the exact errors from the serializer when you are updating.



Related Topics



Leave a reply



Submit