首页 > 解决方案 > 在 django admin 中的 pre_save 上获取文件 mime 类型

问题描述

我想通过获取 pre_save 信号来保存文件 mime 类型。

from django.db.models.signals import pre_save
from django.db import models
import magic

class Media (models.Media):
    file = models.FileField()
    content_type = models.CharField(max_length=128, editable=False)

def media_pre_save(sender, instance, *args, **kwargs):
    if not instance.content_type:
        mime = magic.Magic(mime=True)
        instance.content_type = mime.from_buffer(instance.file.read())
pre_save.connect(media_pre_save, sender=Media)

但是application/x-empty当我在数据库中查看它时我得到了。我究竟做错了什么?

标签: pythondjangodjango-adminmime-types

解决方案


我终于想出了如何获取上传文件的绝对路径并使用如下from_file方法magic

instance.content_type = magic.from_file(instance.file.path, mime=True)

更新的答案:

如果文件有点大,我有时会得到空文件,所以我必须从上传文件的开头“寻找”并使用如下from_buffer方法magic

instance.file.seek(0)
instance.content_type = magic.from_buffer(instance.file.read(), mime=True)

我欠以下链接的答案: 使用 pre_save 信号https://github.com/ahupp/python-magic编辑上传的文件(djangos FileField)


推荐阅读