[英]How to check if a new file was selected in django admin using a pre_save signal?
[英]Get file mime type on pre_save in django admin
我想通過獲取 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)
但是當我在 db 中查看它時,我得到了application/x-empty
。 我究竟做錯了什么?
我終於想出了如何獲取上傳文件的絕對路徑並使用magic
的from_file
方法,如下所示:
instance.content_type = magic.from_file(instance.file.path, mime=True)
更新的答案:
如果文件有點大,我有時會得到空文件,所以我必須從上傳文件的開頭“尋找”並使用magic
的from_buffer
方法,如下所示:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.