栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用当前模型ID的Django管理文件上传

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用当前模型ID的Django管理文件上传

图像文件将在Gallery实例之前保存。因此,您必须通过使用带有状态的Gallery实例本身的信号将保存分为两个阶段:

from django.db.models.signals import post_save, pre_savefrom django.dispatch import receiver_UNSAVED_FILEFIELD = 'unsaved_filefield'@receiver(pre_save, sender=Image)def skip_saving_file(sender, instance, **kwargs):    if not instance.pk and not hasattr(instance, _UNSAVED_FILEFIELD):        setattr(instance, _UNSAVED_FILEFIELD, instance.image)        instance.image = None@receiver(post_save, sender=Image)def save_file(sender, instance, created, **kwargs):    if created and hasattr(instance, _UNSAVED_FILEFIELD):        instance.image = getattr(instance, _UNSAVED_FILEFIELD)        instance.save()     # delete it if you feel uncomfortable...        # instance.__dict__.pop(_UNSAVED_FILEFIELD)

upload_path_handler看起来像

def upload_path_handler(instance, filename):    import os.path    fn, ext = os.path.splitext(filename)    return "site_media/images/gallery/{id}{ext}".format(id=instance.pk, ext=ext)

如果字段仅用于图像上传,我建议使用ImageField而不是FileField进行类型检查。另外,您可能希望规范化文件名扩展名(由于mimetype而不需要),例如

def normalize_ext(image_field):    try:        from PIL import Image    except importError:        import Image    ext = Image.open(image_field).format    if hasattr(image_field, 'seek') and callable(image_field.seek):       image_field.seek(0)    ext = ext.lower()    if ext == 'jpeg':        ext = 'jpg'    return '.' + ext


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404891.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号