欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

django-rest-framework批量上传文件

程序员文章站 2022-06-02 16:13:50
...

models.py

#models
from django.utils.timezone import now
class MoreImage(models.Model):
    """
    多传图片
    """
    del_choices = (('0', '未删除'),('1', '已删除'))
    now = str(now().strftime('%Y_%m'))
    objectType = models.CharField(max_length=30, verbose_name='图片对应模型', help_text='图片对应模型(CharField)')
    objectID = models.PositiveIntegerField(verbose_name='对应模型ID', db_index=True, help_text='对应模型ID(PositiveIntegerField)')
    image = models.ImageField(upload_to='img/patrol/'+now, verbose_name='图片', help_text='图片(ImageField)', null=True, blank=True)
    createdBy = models.CharField(max_length=30, verbose_name='创建者', help_text='创建者(CharField)', blank=True)
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间(DateTimeField)',auto_now_add=True, null=True, blank=True)
    lastEditedBy = models.CharField(max_length=30, verbose_name='最后编辑人', help_text='最后编辑人(CharField', blank=True)
    lastEditedDate = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间(DateTimeField)', auto_now=True, null=True, blank=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除(CharField,可选值:0,1)', choices=del_choices, default='0')
    class Meta:
        verbose_name = '图片'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.objectType
@admin.register(MoreImage)
class MoreImageAdminModel(admin.ModelAdmin):
    list_display = ('objectType', 'objectID', 'image', 'createdBy', 'createdDate', 'lastEditedBy', 'lastEditedDate', 'deleted')

serializers.py

class MoreImageUploadSerializer(serializers.ModelSerializer):
    """
    图片群传查看接口序列化器
    """
    class Meta:
        model = MoreImage
        fields = '__all__'
class ImageUploadSerializer(serializers.ModelSerializer):
    # user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    def __str__(self):
        return self.url
    class Meta:
        model = MoreImage
        fields = '__all__'
class ImageUploadListImgSerializer(serializers.Serializer):
    """
    CZJ
    图片批量传入接口
    通过objectType传入图片对应模型,objectID为对应实例ID
    """
    imgs = serializers.ListField(
        child=serializers.FileField(max_length=100000,
                                    allow_empty_file=False,
                                    use_url=True),write_only=True
    )
    blog_imgs = serializers.ListField(
        child=serializers.CharField(max_length=1000,),read_only=True
    )
    def create(self, validated_data):
        info = self.context['request'].data
        objectType=info['objectType']
        objectID=info['objectID']
        imgs = validated_data.get('imgs')
        images = []
        for index, url in enumerate(imgs):
            image = MoreImage.objects.create(image=url,objectType=objectType,objectID=objectID)
            img = ImageUploadSerializer(image, context=self.context)
            images.append(img.data['image'])
        return {'Upload_imgs':images}

views.py

class MoreImageUploadViewSet(MyModelViewSet):
    """
    图片群传接口
    """
    queryset = MoreImage.objects.filter(deleted__exact='0')
    serializer_class = MoreImageUploadSerializer
    permission_classes = [permissions.IsAuthenticated]
class ImageUploadViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    '''
    create:
    创建图片
    '''
    # authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    queryset = MoreImage.objects.all()
    serializer_class = ImageUploadListImgSerializer
    parser_classes = (MultiPartParser, FileUploadParser,)

urls.py

from rest_framework import routers
from patrol_m import views as PatrolMViews   #导入自己对应的app里面的views
# 定义DRF的API链接
# 使用basename可以解决drf路由被覆盖的问题
router = routers.DefaultRouter()
router.register(r'Images-post', PatrolMViews.ImageUploadViewSet, basename='Images-post')#czj上传图片
router.register(r'Images-get', PatrolMViews.MoreImageUploadViewSet, basename='Images-get')#czj上传图片

postman测试

django-rest-framework批量上传文件
django-rest-framework批量上传文件

相关标签: django学习 django