0

我需要使用 django rest 框架将图像上传到 django 服务器。我尝试使用 httpie 发布图像,但出现此错误。

http 400 未提交图像。

序列化程序.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')

模型.py

from django.db import models

class MyPhoto(models.Model):

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

视图.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)

我已经设置MEDIA_ROOTMEDIA_URL.

4

1 回答 1

0

试试这个方法。这可能会帮助您解决问题。

视图.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() 

网址.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)),
]

只需在浏览器中使用 url http://localhost:8000/photo/

于 2017-02-25T06:13:12.793 回答