Django / Python: change the loaded file name before saving the file.

I am creating a website where users can upload images. I need to make sure that each file name has a unique name so that the files do not overwrite with each other. I will generate a unique name. But how to change the file name before saving the file? I see that there are ways to change the folder in which it is saved, but this is not quite what I need.

class saved_photos(models.Model): name = models.CharField(max_length=20) photo = models.ImageField(upload_to='images/things/', blank=True, null=True) 

In my code, I:

 new_name = get_unique_name() p = saved_photos(name = new_name, photo = request.FILES) p.save() 

I need the actual name of the saved file to be new_name.

+4
source share
2 answers

You need to define upload_to .

+7
source

Django can correctly handle a unique file name. The duplicate name will be renamed automatically. If you want to set the file name manually, just define the upload_to function, as DrTyrsa said. This question may help you.

+1
source

All Articles