Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django unique filename method

I am looking for the method Django uses to generate unique filename when we upload a file.

For example, if I upload a file called test.csv twice in the same directory, the first one will be saved as test.csv and the second file will be saved as test_2.csv. I already tried to find how Django manages that, but I only found django.utils.text.get_valid_filename which could be useful, but that not what I am looking for...

I already saw other topics with random naming solution, that not what I am looking for here :) I really trying to understand how Django manage that problem.

like image 906
Thom Avatar asked Sep 08 '25 07:09

Thom


2 Answers

I actually take a closer look with your help and a found something :)

So basically I have to do something like:

from django.core.files.storage import FileSystemStorage

fss = FileSystemStorage()
filepath = fss.get_available_name(filepath)

Thank you all :)

PS: If you are interesting, the comment from django.core.file.storage.FileSystemStorage._save says:

There's a potential race condition between get_available_name and saving the file; it's possible that two threads might return the same name, at which point all sorts of fun happens. So we need to try to create the file, but if it already exists we have to go back to get_available_name() and try again.

like image 165
Thom Avatar answered Sep 09 '25 20:09

Thom


If you see the implementation of class django.core.files.storage.Storage you will know how Django 1.6 manages the file names.

Look into the save method of this class. In this the line

name = self.get_available_name(name)

is doing the trick.

This is the default implementation of getting the new file name before saving the file. If you want to write your own version (like the file should be overridden) then consider writing your own custom storage system

like image 45
anuragal Avatar answered Sep 09 '25 21:09

anuragal