Search code examples
djangodjango-rest-frameworkhttpie

cannot upload image to django


I need to upload an image to django server with django rest framework. I tried to post the image using httpie and I am getting this error.

http 400 no image was submitted.

serializers.py

from rest_framework import serializers

from myapp.models import *


class PhotoSerializer(serializers.ModelSerializer):


    image = serializers.ImageField(max_length=None,use_url=True)


    class Meta:
        model = MyPhoto
        fields = ('id', 'image')

models.py

from django.db import models

class MyPhoto(models.Model):

    image = models.ImageField(upload_to='photos/', max_length=254)

views.py

from rest_framework.views import APIView
from myapp.models import *
from myapp.serializers import PhotoSerializer
from rest_framework import status
from rest_framework.response import Response
from rest_framework.parsers import FormParser, MultiPartParser


class PhotoList(APIView):

    parser_classes = (FormParser, MultiPartParser)

    def get(self, request, format=None):

        photo = MyPhoto.objects.all()

        serializer = PhotoSerializer(photo, many=True)
        return Response(data=serializer.data, status=status.HTTP_200_OK)

    def post(self, request, format=None):

       serializer = PhotoSerializer(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)

I have setMEDIA_ROOT and MEDIA_URL.


Solution

  • Try this way. this might help you to resolve your issue.

    views.py

    from rest_framework.viewsets import ModelViewSet
    from myapp.models import *
    from myapp.serializers import PhotoSerializer
    
    class PhotoList(ModelViewSet):
        serializer_class = PhotoSerializer
        queryset = MyPhoto.objects.all() 
    

    urls.py

    from django.conf.urls import include, url
    from rest_framework.routers import DefaultRouter
    from myapp.views import PhotoList
    router = DefaultRouter()
    router.register(r'photo', PhotoList, 'photo')
    
    urlpatterns = [
         url(r'^', include(router.urls)),
    ]
    

    Just use url in browser http://localhost:8000/photo/.