How to check if file exists in media folder?

Viewed 2829

Here I successfully uploaded files in database(working fine). The issue here is file is stored in the database and if in case the media folder gets deleted it will raise an error [WinError 2] The system cannot find the file specified: ... So my question is how can I handle this error.

If the file is in database but not in the media folder then I want to handle this error and display the template without error. How can I do this ?

template

{% for document in documents %}
 <tr>
<td>{{forloop.counter}}</td>
 <td>{{document.filename|truncatechars:15}}</td>
 <td>{{document.file.size|filesizeformat}}</td>
 <td>{{document.category}}</td>
 <td>{{document.file.url}}</td>
<tr>
{% endfor %}

models

class Document(models.Model):
    category = models.ForeignKey(DocumentCategory, on_delete=models.CASCADE)
    file = models.FileField(upload_to='media/',
                            validators=[FileExtensionValidator(['pdf', 'xlsx', 'pptx', 'docx','xls']), file_size])
    created = models.DateTimeField(auto_now_add=True)


    @property
    def filename(self):
        return os.path.basename(self.file.name)           
2 Answers

You can use default_storage.exists(path) to determine that.

 from django.core.files.storage import default_storage
 path = 'path/to/file'
 default_storage.exists(path)

But notice that your path must be in the project folder.

if the file exists in the path then the function returns True otherwise False

and there is a path attribute in the Django FileFeild to get path.

  1. Django is not supposed to serve media files on prod, so additional code related to reading regular media files makes not much sense

  2. self.file.name contains path relative to MEDIA_ROOT, so implemented approach is not really correct

  3. since you know about os.path it's not clear what you're actually asking about; there is path.exists method, and more specific os.path.isfile

  4. exceptions can be catched by try-except block as any other exceptions in python.

    try:
        # Do something with the file
    except IOError:
        # Do something in case of error
Related