How to generate unique filename for django model.FileField -


i working on django/python project. project uses model contains filefield. model fed web form. works great: django automatically renames file if existing file same name exists.

i have second model contains filefield. file not uploaded via web form. file content generated on file python program. want provide file name when inserting it. , want django/python rename automatically no web form. how should ?

thanks.

i think using uuid make filename long. may :-

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

note :- adjust length parameter per 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))    = ''.join(random.choice(chars) in range(length))     filename = '%s%s' % (yourfilename,str(a))     storefilename = models.objects.create(filename=filename) 

you can't set unique=true filefield might bugs in django work follows:

apparently, happens this: if file exists, new file named <>., <> number of underscores needed make name unique. so, example, when file named foo.png uploaded multiple times, second file named foo_.png, third foo__.png , on. should documented, though. i'm not sure whether renaming happens in admin code or in model code.

so finnaly, may have 1 option save filename seperately , check in before uploading file.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -