Django Rest Framework无法解析多部分/表单数据

时间:2018-06-21 01:30:40

标签: python django python-3.x rest

如DRF文档http://www.django-rest-framework.org/api-guide/parsers/#multipartparser中所述,为了解析multipart / form-data,必须使用MultiPart和form解析器。我很怀疑这是Django Rest Framework中的问题,因为我在他们的github问题上看到了一个解决方案,说它可以使用API​​View运行。

from django.contrib.auth.models import User
from rest_framework import viewsets
from api.serializers import UserSerializer,

from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all()
    parser_classes = (MultiPartParser, FormParser)
    serializer_class = UserSerializer

我向邮递员发送请求的图片,结果: Picture of me sending request to Postman with result

编辑:添加UserSerializer类

class UserSerializer(serializers.HyperlinkedModelSerializer):
    snapcapsules = SnapCapsuleSerializer(
        many=True,
        read_only=True,
        allow_null=True,
    )

    class Meta:
        model = User
        fields = ('snapcapsules', 'url', 'username', 'email', 'password', )
        write_only_fields = ('password',)

    def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
        )

        user.set_password(validated_data['password'])
        user.save()

        return user

    def update(self, instance, validated_data):
        capsules_data = validated_data.pop('snapcapsules')

        for capsule in capsules_data:
             SnapCapsule.objects.create(user=instance, **capsule)

        return instance

Picture of what I of what I requested

2 个答案:

答案 0 :(得分:2)

ContentType可能不是问题。错误响应指出,UserSerializer期望payloaddata,其中包括usernamepassword字段

因此,请尝试将这些字段添加到请求正文中,然后重试 POstman ScreenShot

更新

Orginal Post的问题是,他在POSTMAN中添加了额外的标头(请参见下图)

enter image description here

邮递员会为您添加适当的标题。因此,您不必明确提及它

答案 1 :(得分:2)

我删除了一行,然后奏效了!

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

此外,可以如下重写串行器:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    ...

    def create(self, validated_data):
        return User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            password=validated_data['password']
        )

    ...