Building Blocks if there’s one thing I know about me and my thoughts: given enough time I’m always wrong

12Sep/080

Dynamic upload paths in Django

I'm refactoring my VE:Session application a bit to the recently released Django 1.0. They have made some outstanding progress with the project overall, but there are enough things that are radically different to cause me to lose sleep searching for answers to small problems. I'd simply overlooked their NewForms branch when I was building the application, and now I am paying for it by standing well behind the curve. It is fun to learn new things though, so that is the upside I suppose.

Anyway, back to the refactoring. In addition to updating the project to the current Django trunk, I want to unify the application under Django. I am currently using SlideshowPro for my image CMS functionality. It is a fine product, but it obsfusicates the application and certainly makes it harder to deploy. This is compounded by the fact that I am using an older version of SSP. Django has some out of the box options for filing your uploads in a data structure. I really need something more customizable for the application though, and I was feverishly searching for a solution. The previous examples were complex hacks to get the job done. Which is fine, but they are now broken with the update to 1.0. D'oh. As luck would have it they are not neccesary any longer, and the same functionality can be added with a few simple lines that Scott Barnham was kind enough to demonstrate:

1
2
3
4
5
6
7
from django.db import models
 
def get_image_path(instance, filename):
    return 'photos/%s/%s' % (instance.id, filename)
 
class Photo(models.Model):
    image = models.ImageField(upload_to=get_image_path)

Awesome.

I've been knee deep in Java for the past few months, so it is really nice to get back into Python for a bit. With Django reaching a comfortable level of maturity, I see many more sleepless nights in my future.

Creative Commons License
The Dynamic upload paths in Django by Joel Hooks, unless otherwise expressly stated, is licensed under a Creative Commons Attribution 3.0 United States License.
Filed under: django, python Leave a comment
blog comments powered by Disqus