首页 > 解决方案 > 无法读取 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', '系统找不到指定的文件。')

标签: pythondjangodjango-modelsdjango-file-upload

解决方案


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


推荐阅读