169π
Use uuid. To tie that into your model see Django documentation for FileField upload_to.
For example in your models.py define the following function:
import uuid
import os
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('uploads/logos', filename)
Then, when defining your FileField/ImageField, specify get_file_path
as the upload_to
value.
file = models.FileField(upload_to=get_file_path,
null=True,
blank=True,
verbose_name=_(u'Contact list'))
20π
A better way could be using a common class in your helpers.py. This way you could reuse the random file generator across your apps.
In your helpers.py:
import os
import uuid
from django.utils.deconstruct import deconstructible
@deconstructible
class RandomFileName(object):
def __init__(self, path):
self.path = os.path.join(path, "%s%s")
def __call__(self, _, filename):
# @note It's up to the validators to check if it's the correct file type in name or if one even exist.
extension = os.path.splitext(filename)[1]
return self.path % (uuid.uuid4(), extension)
And then in your model just import the helper class:
from mymodule.helpers import RandomFileName
And then use it:
logo = models.ImageField(upload_to=RandomFileName('logos'))
Ref: https://coderwall.com/p/hfgoiw/give-imagefield-uploads-a-unique-name-to-avoid-file-overwrites
- [Django]-Django β Reverse for '' not found. '' is not a valid view function or pattern name
- [Django]-How can I call a custom Django manage.py command directly from a test driver?
- [Django]-How to delete a record in Django models?
12π
As of the writing of this answer it seems like you no longer need to do anything special to make this happen. If you set up a FileField
with a static upload_to
property, the Django storage system will automatically manage naming so that if a duplicate filename is uploaded, Django will randomly generate a new unique filename for the duplicate.
Works on Django 1.10.
- [Django]-Django 1.4 β can't compare offset-naive and offset-aware datetimes
- [Django]-Django: Fat models and skinny controllers?
- [Django]-Celery: When should you choose Redis as a message broker over RabbitMQ?
9π
Prior to Django 1.6.6, 1.5.9, and 1.4.14, the get_avaialable_name
function would automatically give files a unique name by adding an underscore. So, for example, if you save one file βtest.jpgβ and then another file, βtest.jpgβ to your server, the first will be called test.jpg, and the second will be called test_1.jpg.
Alas, that turns out to be a vector for DDOSing a machine, by sending it thousands of zero-byte files to store, each one checking thousands of previous files to see what its name should be.
As youβll see in the docs, the new system appends seven random digits after the underscore to fix this problem.
- [Django]-How do I check for last loop iteration in Django template?
- [Django]-How to access outermost forloop.counter with nested for loops in Django templates?
- [Django]-Django Template Language: Using a for loop with else
3π
You can write your own FileField
and override generate_filename
.
For example:
class UniqueNameFileField(FileField):
def generate_filename(self, instance, filename):
_, ext = os.path.splitext(filename)
name = f'{uuid.uuid4().hex}{ext}'
return super().generate_filename(instance, name)
- [Django]-Check if celery beat is up and running
- [Django]-How do I go straight to template, in Django's urls.py?
- [Django]-Elegant setup of Python logging in Django
0π
How about concatenating the filename with the date / time the photo was uploaded and then using hashlib to create a message digest? That should give you unique filenames.
Alternatively you could re-use a neat little snippet which creates unique filenames and then use the full path to that file as the input to your hash call. That gives you unique constant length strings which you can map to your files.
- [Django]-Silence tqdm's output while running tests or running the code via cron
- [Django]-Django: Where to put helper functions?
- [Django]-How to completely uninstall a Django app?
0π
django enforce unique filename automatically.
if the file already exists, seven unique characters are appended to the filename
tested on django 2.2
- [Django]-.filter() vs .get() for single object? (Django)
- [Django]-How do I filter query objects by date range in Django?
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable