Django Rest Framework无法解析多部分/表单数据 [英] Django Rest Framework unable to parse multipart/form data
问题描述
如DRF文档中所述
ContentType
可能不是问题.错误响应表明, UserSerializer
期望一个 payload
或 data
,其中包括 username
和密码
字段
因此,请尝试将这些字段添加到请求正文中,然后重试
更新
.
邮递员会为您芳香地添加适当的标题.因此,您不必明确提及它
As stated in DRF documentation http://www.django-rest-framework.org/api-guide/parsers/#multipartparser, in order to parse multipart/form-data, the MultiPart and form parser must be used. I have a supiscion this is a problem in the Django Rest Framework because I saw a solution on their github issue saying it work using APIView.
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:
Edit: Adding UserSerializer class
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
This is might not the issue with the ContentType
. The error response says that,the UserSerializer
excpect a payload
ordata
which include username
and password
field
So, Please try to add those fields to the request body and try again
UPDATE
The problem with the .
Postman will add appropriate Headers aromatically for you. So, you don't have to explicitly mention it
这篇关于Django Rest Framework无法解析多部分/表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!