簡體   English   中英

在 django admin 中的 pre_save 上獲取文件 mime 類型

[英]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 我究竟做錯了什么?

我終於想出了如何獲取上傳文件的絕對路徑並使用magicfrom_file方法,如下所示:

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

更新的答案:

如果文件有點大,我有時會得到空文件,所以我必須從上傳文件的開頭“尋找”並使用magicfrom_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM