Django filestorage save method creates path dependent on filename

434 views Asked by At

I am trying to work with a filestorage in Django. Everything is working fine but a thing in my save method I guess. I have a model with a FileField

download_url = models.FileField(verbose_name = 'Konfig', upload_to = file_path, storage = OverwriteStorage())

In this method in my model I create the file_path

def file_path(instance, filename):
        path = os.getcwd() + '/files'
        return os.path.join(path, str(instance.download_url), filename)

And the filestorage method I use is outsourced in my storage.py which I import in my models.py

from django.core.files.storage import FileSystemStorage

class OverwriteStorage(FileSystemStorage):

    def _save(self, name, content):
        if self.exists(name):
            self.delete(name)
        return super(OverwriteStorage, self)._save(name, content)

    def get_available_name(self, name):
        return name

Now when I create a new file in the admin interface from django, it successfully uploads the file, makes a database entry with the correct filepath, but it fails to create the right path. When my filename is foo the path would look like following:

cwd/files/foo/foo

and if its name would be bar.txt it would look like following:

cwd/files/bar.txt/bar.txt

I don't want django to create a subdirectory based on the filename. Can you guys help me out ?

1

There are 1 answers

1
Patrik On

Im pretty sure you have to rename the save function from "save" to "_save".

On the Super Call, you used ._save, which isnt the same function as the save function above.

You can read alot about Super here