Unable to read Django FileField?

django read uploaded file
django read filefield
django imagefield example
django fieldfile
django save file to disk
django upload file without form
django filesystemstorage
django file server

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.

Managing files | Django documentation, When you use a FileField or ImageField , Django provides a set of APIs you can actually understands things like file systems, opening and reading files, etc. FileField and ImageField are created as a string field in the database (usually VARCHAR), containing the reference to the actual file. If you delete a model instance containing FileField or ImageField, Django will not delete the physical file, but only the reference to the file. The request.FILES is a dictionary-like object.

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!

The File object | Django documentation, The File class is a thin wrapper around a Python file object with some of its file object: encoding , fileno , flush , isatty , newlines , read , readinto , readline This will not replace the existing file, but will create a new file and update the object� However, if an uploaded file is too large, Django will write the uploaded file to a temporary file stored in your system’s temporary directory. On a Unix-like platform this means you can expect Django to generate a file called something like /tmp/tmpzfp6I6.upload. If an upload is large enough, you can watch this file grow in size as Django

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.

File Uploads | Django documentation, A view handling this form will receive the file data in request.FILES , which is a dictionary containing a key for each FileField (or ImageField , or other FileField� We will use Pipenv to install both Django and pillow which is a Python image process library Django relies on for image files. For non-image file uploads, pillow is not needed. Finally activate our new virtual environment with the shell command.

FileField - Django Models, FileField is a file-upload field. Django Model FileField Explanation editable, If False, the field will not be displayed in the admin or any other ModelForm. By using our site, you acknowledge that you have read and� django-users mailing list Search for information in the archives of the django-users mailing list, or post a question. #django IRC channel Ask a question in the #django IRC channel, or search the IRC logs to see if it’s been asked before. Ticket tracker Report bugs with Django or Django documentation in our ticket tracker. Download:

Django: Image Files Uploading Example - 2020, This defines a Form class with a single field (docfile) of FileField. View: myproject/ myapp/views.py. Our code: from django.shortcuts import render_to_response� Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them.

Usage - django-filer's documentation!, FileField and django.db.models.ImageField. The django-filer versions provide the added benefit of being able to manage the files independently of where they � In this article we will discuss how to upload a csv file and then process the content without storing file on server. One approach could be uploading the file, storing it in upload directory and then reading the file.

Comments
  • what is the value of str(File.file)?
  • Printing them gave me : File Field: <django.db.models.fields.files.FileDescriptor object at 0x000001E7E2F59B00> File Field Type: <class 'django.db.models.fields.files.FileDescriptor'>
  • What is this? custom.storage import AzureMediaStorage?
  • That's to define my custom storage (Azure). I store the files in blob storage on Azure!!
  • Hey!! When I try File.file.path, I get the error: AttributeError: 'FileDescriptor' object has no attribute 'path'
  • Hey! I continue to get the File not found error. Also, printing File.file_name returns: File_Name Field: <django.db.models.query_utils.DeferredAttribute object at 0x000002EA91953080> File Name Type: <class 'django.db.models.query_utils.DeferredAttribute'>
  • what you probably want is os.path.join(settings.MEDIA_ROOT, self.file.name)
  • @Abhishek Using default_storage.exists(path) gives the error: AttributeError: 'DeferredAttribute' object has no attribute 'replace' . (This can be understood better, with reference to the error in my above comment)
  • I suspected this, but thanks for pointing out. But I have configured Django to communicate with Azure. So, how exactly should I go about solving this ?