我需要使用 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_ROOT
和MEDIA_URL
.