[Django]-How to generate unique filename for django model.FileField

1πŸ‘

βœ…

I think using UUID will make your filename so long. This may also help you :-

  import os, random, string
  length = 13
  chars = string.ascii_letters + string.digits + '!@#$%^&*()'
  random.seed = (os.urandom(1024))
  a = ''.join(random.choice(chars) for i in range(length))

Note :- Adjust the length parameter as per your wish.

filename = '%s%s' % (Yourfilename,str(a))

Change models.py as:

fileName = CharField(max_length=10, blank=True,unique=True)

Change views.py as:

try:
    filename  = filename
    storeFileName = models.objects.create(fileName=filename) 
except Exception,e:
   import os, random, string
   length = 13
   chars = string.ascii_letters + string.digits + '!@#$%^&*()'
   random.seed = (os.urandom(1024))
   a = ''.join(random.choice(chars) for i in range(length))

   filename = '%s%s' % (Yourfilename,str(a))

   storeFileName = models.objects.create(fileName=filename)

You can’t set unique=True for fileField this might be bugs in Django it will work as follows:

Apparently, what happens is this:
If the file already exists, the new file will be named <>., where <> is the number of underscores needed to make the name unique. So, for example, when a file named foo.png is uploaded multiple times, the second file will be named foo_.png, the third will be foo__.png and so on.
This should probably be documented, though. I’m not sure whether this renaming happens in the admin code or in the model code.

So finnaly, you may have only one option to save filename seperately and check in that before uploading file.

4πŸ‘

I think the simplest way to do this is explained in this answer:

https://stackoverflow.com/a/10501355/3848720

You could either just call the filename a universally unique identifier (UUID) as in the answer above. Or you could append the UUID onto the existing name as follows:

import uuid

filename = '%s%s' % (existing_filename, uuid.uuid4())
πŸ‘€tdsymonds

Leave a comment