4

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.

user984003
  • 28,050
  • 64
  • 189
  • 285

2 Answers2

8

You need to define upload_to function.

DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
  • Doesn't that just change the file location, not the filename? I want all my files to be saved in the same folder. – user984003 Oct 21 '11 at 09:34
  • Can you give a code example, because I'm not seeing how. Is there a name attribute that I can change?? – user984003 Oct 21 '11 at 10:03
  • @user984003 the function generates a path which will be appended to your `MEDIA_ROOT`. If it return the string `blablabla.jpg`, every file will be saved in `MEDIA_ROOT` as `blablabla.jpg`. – DrTyrsa Oct 21 '11 at 10:15
  • 3
    Thanks, that worked. In my model I added the field "photo = models.ImageField(upload_to=get_path_and_name)". Then in models.py I also defined a function: def get_path_and_name(instance, filename): new_name = 'blabla.jpg' return new_name – user984003 Oct 21 '11 at 14:45
  • And also, Clippit is right, duplicate file name are renamed automatically. – user984003 Oct 21 '11 at 14:47
1

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.

Community
  • 1
  • 1
Clippit
  • 856
  • 1
  • 9
  • 20