这是我的模型的样子:
class ExampleModel(models.Model):
text = models.CharField(max_length=2)
image = models.ImageField(upload_to='Thats all set. Dont worry about it.')
我有一个标准的序列化器:
class ExampleSerializer(serializers.ModelSerializer):
class Meta:
model = ExampleModel
fields = "__all__"
然后有我的看法:
class ExampleView(viewsets.ModelViewSet):
queryset = ExampleModel.objects.all()
serializer_class = ExampleSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
parser_classes = (MultiPartParser, FormParser)
def post(self, request, *args, **kwargs):
file_serializer = ExampleSerializer(data=request.data)
if file_serializer.is_valid():
file_serializer.save()
return Response(file_serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我想知道的是
a)我正在尝试使用Python请求填充文本和模型字段。
requests.post(url, headers="The tokens(Already taken care of)", "How to put in the body? Where and how do I add the image and text?"
b)是否需要更改或添加序列化程序,视图或其他内容以满足我的要求?
感谢您的帮助。谢谢您阅读本文的时间:)
编辑:而且,如何更新已经存在的对象?我只能在较老的Django中找到它。
答案 0 :(得分:0)
a)您可以像这样发布文字和图片:
image_file = {'image': open('test.jpg', 'rb')}
headers = {
'Content-Type': 'multipart/form-data',
}
jsondata = {'text': 'hello_world'}
requests.post(url, headers=headers, data=jsondata, files=image_file)
b)无需更新序列化程序