gpt4 book ai didi

python - Rest 框架中的 HTML 输入目前不支持列表

转载 作者:行者123 更新时间:2023-12-01 03:57:10 26 4
gpt4 key购买 nike

我想设计一个 API 来创建租金信息和画廊(多个图像上传)。我的模型看起来是这样的

class Rental(models.Model):
ownerName = models.CharField(_("Owner's Name"),max_length=255, blank=True,null=True,
help_text=_("Owner's Full Name"))
renter = models.ForeignKey(User,null=True,blank=True)
email = models.CharField(max_length=120,blank=True,null=True)
phoneNumber = models.PositiveIntegerField(blank=False,null=True,
help_text=_("Phone number of contact person"))

class Gallery(models.Model):
rental = models.ForeignKey('Rental', null=True, on_delete=models.CASCADE,verbose_name=_('Rental'), related_name="gallery")
image = models.ImageField(blank=True,upload_to='upload/',null=True)

序列化器.py

class GalleryListSerializer(ModelSerializer):
class Meta:
model = Gallery

class RentalCreateUpdateSerializer(ModelSerializer):
gallery = GalleryListSerializer(many=True)
class Meta:
model = Rental
exclude = ('id','slug','is_published','created_on','modified_on',)

views.py

class RentalCreateAPIView(CreateAPIView):
queryset = Rental.objects.all()
serializer_class = RentalCreateUpdateSerializer
# permission_classes = [IsAuthenticated]

def perform_create(self, serializer):
serializer.save(user=self.request.user)

def create(self,validated_data):
ownerName=validated_data.get('ownerName',None)
renter = validated_data.get('renter', None)
email=validated_data.get('email',None)
phoneNumber=validated_data.get('phoneNumber',None)
image=validated_data.pop('image')
return Rental.objects.create(ownerName=ownerName,renter=renter,phoneNumber=phoneNumber,email=email,image=image)

如何为每次租金启用多个图像上传?我得到的是

enter image description here

最佳答案

目前尚不清楚您是在询问可浏览 API 渲染器中的文件上传表单,还是纯粹在询问 Django 中用于保存和显示图像的管道。我正在回答有关管道的问题,即上传和保存。

使用 REST API 上传文件的教程,也许可以先阅读此内容以获得更好的背景知识:https://medium.com/@jxstanford/django-rest-framework-file-upload-e4bc8de669c0#.i5pun7abs

注意他们如何在 FileUploadViewSet 中设置解析器。这个 FileUpload 模型就像您的 Gallery 模型。您应该能够将 parser_classes 添加到您的 CreateAPIView 中,如下所示:

# views.py
from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework.viewsets import ModelViewSet
from probably.obtain.models import FileUpload
from probably.obtain.serializers import FileUploadSerializer


class FileUploadViewSet(ModelViewSet):

queryset = FileUpload.objects.all()
serializer_class = FileUploadSerializer
parser_classes = (MultiPartParser, FormParser,)

def perform_create(self, serializer):
serializer.save(owner=self.request.user,
datafile=self.request.data.get('datafile'))

阅读本文,了解有关如何/何时选择解析器的更多详细信息,以及更多片段:http://www.django-rest-framework.org/api-guide/parsers/

关于python - Rest 框架中的 HTML 输入目前不支持列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37245989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com