Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django / Python : Change uploaded filename before saving file

I am creating a site where users can upload images. I need to make sure that each filename has a unique name to prevent the files from overwriting each other. I will generate the unique name. But how do I change the filename before saving the file? I see that there are ways to change the folder that it is saved to, but that's not quite what I'm after.

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 do:

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

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

like image 805
user984003 Avatar asked Feb 23 '23 15:02

user984003


2 Answers

You need to define upload_to function.

like image 124
DrTyrsa Avatar answered Feb 25 '23 04:02

DrTyrsa


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

like image 41
Clippit Avatar answered Feb 25 '23 04:02

Clippit