Django upload_to trickery

I’ve recently discovered Django and have used it for all my web development projects ever since. If you’re doing web development in Python do yourself a favour and check it out.

I’ve just spent too many hours figuring out a way to make Django store an uploaded image in a directory depending on another field of the model, but I finally made it work and I figured I’d share it with the world. It may not be pretty, but it makes sense to me.

Well, it all boils down to overriding the save() method. Like so:

class Illustration(models.Model):
    item = models.ForeignKeyField(Item)
    image = models.ImageField(upload_to='images/incoming')

    def save(self):
        for f in self._meta.fields:
            if f.attname == 'image':
                f.upload_to = 'images/items/%d/' %

        super(Illustration, self).save()

If anyone should care, I need it for a new website for my girlfriend. The current one can be seen here for a few days until I make the transition to this new Django-powered one.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>