简体   繁体   中英

Unable to read Django FileField?

I am trying to read from Django Filefield , as can be seen in my Django Model:

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)

But os.path.isfile() keeps returning False . How do I read from FileField, into my custom model ?

And moreover, the line fixedInfo , gives me the error:

pywintypes.error: (2, 'GetFileVersionInfo:GetFileVersionInfoSize', 'The system cannot find the file specified.')

os.path.isfile returns whether the filepath is pointing to a file (as opposed to a directory, for instance). File.file is pointing to a models.FileField object; the current code will always return False . I suppose you would want File.file.path to get the actual absolute filepath for the file.

In your model definition you may add:

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

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

Or you may try:

from django.core.files.storage import default_storage

Use: 1) FieldFile.name:

The name of the file including the relative path from the root of the Storage of the associated FileField.

2) default_storage.exists(path)

Return True if a file referenced by the given name already exists in the storage system, or False if the name is available for a new file.

Hope this works!

As you are using a different storage provider for your files, you need to use the methods of that storage provider to query the file object.

os.path.isfile and win32api.GetFileVersionInfo only work for the local file system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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