Today we are going to learn a new topic. When we upload the file, the file will be saved with the name that is in your local storage. It has more possibility to get the same name for multiple files. That’s why we need to create a unique name for the same file name in local storage. You can follow the file system in Django’s official documentation. In this tutorial, I am sharing the way that creates the unique file name for upload file in Django. To do so, first of all, open models.py file and rewrite the file instance field like the following snippet.
from functools import partial class GalleryContent(models.Model): image=models.ImageField(upload_to=partial(make_filepath, 'gallery'))
The first line of the code: we import partial for creating a directory as upload directory. It will create a new directory named gallery on your media path. If we change the text ‘gallery’ in the second parameter of the partial method in image instance, it will take that name also.
Now implement the make_filepath function with the following coding snippet.
from django.contrib.auth.models import User def make_filepath(directory, instance, filename): new_filename = "%s.%s" % (User.objects.make_random_password(10),filename.split('.')[-1]) return '/'.join([directory, new_filename])
It means you are going to create a unique name using the random password making function for logged in user and add them to the directory also.