繁体   English   中英

无法读取Django FileField?

[英]Unable to read Django FileField?

我试图从Django Filefield中读取,我的Django模型中可以看到:

import os
import win32api

from django.db import models
from custom.storage import AzureMediaStorage as AMS

class File(models.Model):
    '''
    File model
    '''
    file = models.FileField(blank=False, storage=AMS(), null=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    remark = models.CharField(max_length=100, default="")

class File_Version(File):
    """
    Model containing file version information
    """
    version = models.CharField(max_length=25, default="")

    @property
    def get_version(self):
        """
        Read all properties of the given file and return them as a dictionary
        """   

        props = {'FileVersion': None}

        # To check if the file exists ?
        ### This returns FALSE
        print("Is the file there? ", os.path.isfile(str(File.file)) )

        # To get file version info
        fixedInfo = win32api.GetFileVersionInfo(str(File.file), '\\')
        print("FixedInfo: ", fixedInfo)

但是os.path.isfile()一直返回False 如何从FileField读取我的自定义模型?

而且, fixedInfo行给了我错误:

pywintypes.error:(2,'GetFileVersionInfo:GetFileVersionInfoSize','系统找不到指定的文件。')

os.path.isfile返回文件路径是否指向文件(例如,与目录相对)。 File.file指向models.FileField对象; 当前代码将始终返回False 我想你会希望File.file.path获取文件的实际绝对文件路径。

在您的模型定义中,您可以添加:

class File(models.Model):
    file = models.FileField()
    ...
    ...

    def filename(self):
        return os.path.basename(self.file.name)

或者您可以尝试:

来自django.core.files.storage import default_storage

使用:1)FieldFile.name:

文件名,包括相关FileField的Storage根目录的相对路径。

2)default_storage.exists(path)

如果存储系统中已存在由给定名称引用的文件,则返回True;如果该名称可用于新文件,则返回False。

希望这个有效!

在为文件使用不同的存储提供程序时,需要使用该存储提供程序的方法来查询文件对象。

os.path.isfilewin32api.GetFileVersionInfo仅适用于本地文件系统。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM