Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use django.core.files.storage.get_available_name?

I am storing files and need a unique file name. I found a suggestion to use django.core.files.storage.get_available_name but I am completely missing something. I tried this:

class MyModel(models.Model):
    name         = models.CharField( max_length=200, null=True ) 
    filecontent  = models.FileField( null=True, upload_to=Storage.get_available_name(name) )

And got the error: TypeError: unbound method get_available_name() must be called with Storage instance as first argument (got CharField instance instead) which I interpret as meaning that I am trying to run the method on the class but that I need a storage-instance to run it on. There exist something called DefaultStorage which is supposed to be something that "provides lazy access to the current default storage system" but that one does not have the get_available_name method but only a method _setup which can't be called on the class either. So how am I supposed to get an instance to work on here?

like image 576
jonalv Avatar asked Oct 19 '22 10:10

jonalv


1 Answers

The upload_to argument is for directory path that you want to upload your files to. The argument for storage is named just storage

So what you should do if you want to change default Django's Storage implementation is to use for example

    filecontent = models.FileField(null=True, upload_to='path/to/dir', storage=FileSystemStorage())

If you need to implement your own way to play with filenames you just have to create class that inherits from Storage and to overwrite it's get_available_name method. For example:

    class MyOwnStorage(FileSystemStorage):
        def get_available_name(self, name):
            if self.exists(name):
                #return something
            else:
                #return something_else

and then use it as follows:

    filecontent = models.FileField(null=True, upload_to='path/to/dir', storage=MyOwnStorage())
like image 135
m.antkowicz Avatar answered Nov 01 '22 14:11

m.antkowicz