在python/Django中上传一个文件



我有一个问题,我正在使用 django rest 框架,我需要使用 Web 服务将图像提交到服务器,但是我没有找到任何我实际需要的东西,我只想提供文件的位置并让服务完成上传它的工作,有没有办法实现它? ofc 我只会将文件路径保存在 DB 上

class AdvertisementData(EmbeddedDocument):
 id = ObjectIdField(null=False, primary_key=True)
 brand = StringField(max_length=200, required=False)
 name = StringField(max_length=200, required=False)
 description = StringField(max_length=200, required=False)
 image = StringField(required=False)//HERE THE FILEPATH
 active = BooleanField(required=True)
 target = EmbeddedDocumentField('TargetData')

我应该在这个序列化过程中这样做

class AdvertisementDataCreateSerializer(DocumentSerializer):
brand = serializers.CharField(required=True)
name = serializers.CharField(required=True)
description = serializers.CharField(required=True)
image = serializers.CharField(required=True)
active = serializers.BooleanField(required=True)
target = TargetDataSerializer(required=True)

class Meta:
    model = AdvertisementData
    fields = ('brand', 'name','description','image','active','target')
def create(self,validated_data,**kwargs):
    vendor_id = VendorData.objects.get(vendorAuth__idp=self.context['request'].user.id)
    print(vendor_id.id)
    advertisement = AdvertisementData(id=ObjectId(), brand=self.data.get('brand'), name=self.data.get('name'),
              description=self.data.get('description'),image=self.data.get('image'), active=self.data.get('active'))
    targetaux = self.data.get('target')     
    target = TargetData(id=ObjectId(),minAge=targetaux['minAge'],maxAge=targetaux['maxAge'],gender=targetaux['gender'])
    advertisement.target = target
    vendor_id.advertisements.append(advertisement)
    vendor_id.save()
    #advertisement =  [x for x in vendor_id.advertisements if x.id == ObjectId((advertisement.id))]
    vendor_id.save()
    return advertisement

但是我不知道该怎么做,我能够提供文件位置的完整路径,但不知道如何提交它。

最后我发现模型的简洁解决方案是这样的

class AdvertisementData(EmbeddedDocument):
id = ObjectIdField(null=False, primary_key=True)
brand = StringField(max_length=200, required=False)
name = StringField(max_length=200, required=False)
description = StringField(max_length=200, required=False)
image = ImageField(required=False)
active = BooleanField(required=True)
target = EmbeddedDocumentField('TargetData')

class AdvertisementDataCreateValidatorSerializer(DocumentSerializer):
brand = serializers.CharField(required=True)
name = serializers.CharField(required=True)
description = serializers.CharField(required=True)
image = serializers.CharField(required=True)
active = serializers.BooleanField(required=True)
target = TargetDataSerializer
#C:UsersGrupoBECM09PicturesTest
class Meta:
    model = AdvertisementData
    fields = ('brand', 'name','description','image','active','target')
很难

找到这个解决方案,但显然我为我找到了唯一的方法

相关内容

  • 没有找到相关文章

最新更新