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.
You need to define upload_to
function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With