Search code examples
pythondjangofile-upload

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.


Solution

  • You need to define upload_to function.