[英]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.isfile
和win32api.GetFileVersionInfo
僅適用於本地文件系統。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.