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/' % self.item.id
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.
Pages
Recent comments
- Mark Unwin on All the things wrong with monitoring today – Part 2
- Soren on All the things wrong with monitoring today – Part 2
- Joan on All the things wrong with monitoring today – Part 2
- Soren on All the things wrong with monitoring today – Part 2
- Christian on All the things wrong with monitoring today – Part 2
Archives
- January 2012 (1)
- October 2011 (1)
- September 2011 (2)
- August 2011 (1)
- June 2011 (2)
- February 2011 (2)
- January 2011 (2)
- October 2010 (1)
- July 2010 (1)
- May 2010 (3)
- April 2010 (3)
- January 2010 (1)
- March 2009 (3)
- January 2009 (2)
- January 2007 (3)
- September 2006 (1)
Categories
- Cloud computing (5)
- Code (11)
- OpenStack (3)
- Rackspace (5)
- Ubuntu (17)
- Uncategorized (2)
- Work (8)
Blogroll




