Login

Overwrite File Storage System

Author:
sethtrain
Posted:
August 13, 2008
Language:
Python
Version:
.96
Score:
5 (after 5 ratings)

This is a simple implementation overwrite of the FileSystemStorage. It removes the addition of an '_' to the filename if the file already exists in the storage system. I needed a model in the admin area to act exactly like a file system (overwriting the file if it already exists).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import os

from django.conf import settings
from django.core.files.storage import FileSystemStorage

class OverwriteStorage(FileSystemStorage):
    
    def get_available_name(self, name):
        """
        Returns a filename that's free on the target storage system, and
        available for new content to be written to.
        """
        # If the filename already exists, remove it as if it was a true file system
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

juziel (on November 12, 2008):

Sweet... simple and effective. One small comment... it might be slightly better to change the deletion to instead be:

self.delete(name)

as FileSystemStorage provides the method.

#

cameronoliver (on February 23, 2009):

For those confused how to implement this, put the function in your models.py file and use storage=OverwriteStorage() on your FileField declarations.

For example,

powerpoint_file = models.FileField(upload_to="songs/", storage=OverwriteStorage(), blank=True)

#

Please login first before commenting.