Cannot serialize or save uploaded an image in APIview. If saving, a file is broken and cannot be open. If serialzing, getting: {"avatar":["No file was submitted."]} Request content:
MultiValueDict: {u'name': [<TemporaryUploadedFile: Avatar.jpg (image/jpeg)>]}
Settings:
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
URLs:
urlpatterns = [
url(r'^test/$', TestReturn.as_view(), name='test-detail'),
url(r'^users/$', UserProfileAll.as_view(), name='userprofile-detail'),
url(r'^avatar/', UploadAvatar.as_view(), name='images')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Model:
class AvatarStorage(models.Model):
avatar = models.ImageField(verbose_name="Uploaded image", upload_to='media', null=True)
Serialzier:
class AvatarStorageSerializer(serializers.ModelSerializer):
avatar = serializers.ImageField(use_url=True)
class Meta:
model = AvatarStorage
fields = '__all__'
Views:
class UploadAvatar(APIView):
parser_classes = (MultiPartParser,)
def post(self, request, format=None):
serializer = AvatarStorageSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
For posting, i am using Postman, over there settings: Body=>Form-Data and choosing a file from disk.
If it's important, this is API for mobile
The problem was not in the code, I was missing required headers in Postman:
Content-Disposition: attachment; filename=upload.jpg;