无法将图片上传到django

时间:2017-02-24 15:27:26

标签: django django-rest-framework httpie

我需要使用django rest框架将图像上传到django服务器。我试图使用httpie发布图像,我收到了这个错误。

http 400没有提交图片。

serializers.py

vc.loadProductWithParameters([SKStoreProductParameterITunesItemIdentifier : NSNumber(value: 364709193)]

models.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')

views.py

from django.db import models

class MyPhoto(models.Model):

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

我已设置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

1 个答案:

答案 0 :(得分:0)

试试这种方式。这可能有助于您解决问题。

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)),
]

只需在浏览器http://localhost:8000/photo/中使用网址。