views:

22

answers:

1

I have a model:

class Foo(models.Model):
    poster = models.ImageField(u"Poster", upload_to='img')

I'm using the admin to upload posters and save Foo objects. I now need to find a way to lowercase the filename before save. For instance POSTER.png or Poster.png or poster.PNG should be lowercased to poster.png.

What would be the easiest way to achieve this?

+4  A: 

FileField.upload_to may also be a callable, per this comment in the documentation:

This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are:

Since ImageField inherits all its attributes and methods from FileField, I think you could use:

def update_filename(instance, filename):
    path_you_want_to_upload_to = "img"
    return os.path.join(path_you_want_to_upload_to, filename.lower())

class Foo(models.Model):
    poster = models.ImageField(u"Poster", upload_to=update_filename)
Dominic Rodger
Works perfectly, thanks Dominic!
Hellnar
Then mark as correct answer :)
giolekva