python - 在 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
当我在数据库中查看它时我得到了。我究竟做错了什么?
解决方案
我终于想出了如何获取上传文件的绝对路径并使用如下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)
推荐阅读
- javascript - 将插入符号放置到 contenteditable div 的下一个孩子
- node.js - 使用LinkedIn API节点js上传图片
- flutter - 在 SingleChildScrollView 中使用展开的网页浏览
- salesforce - 用于拨打外线电话的 Salsforce 和 Plivo 集成
- javascript - 如何延迟页面渲染,直到从 api 接收到数据
- javascript - 警告:在 StrictMode 中不推荐使用 findDOMNode。findDOMNode 被传递了一个在 StrictMode 中的 Transition 实例。抽屉打开时显示
- c# - 辅助功能(C# 中的 AccessibleObject)不读取屏幕文本
- java - Spring调用oracle函数时如何获取输出参数
- python - 无法在 python 中找出茎叶图中图形的点位置
- python - 带有布尔输出的 ELSEIF 语句