Posts tagged with python:

Django’s upload_to

Went looking for info on how to dynamically assign paths to uploaded content in a Django app. Found this post and tried it out. Either I have an issue with my attempt or that site is referencing old material.

In that post they claim that the upload_to callable will take 3 arguments. However in reality (or at least with my code, django 1.0+) it only takes two:

def get_path(instance, filename):
    return settings.MEDIA_ROOT, 'something', \
           instance.slug, filename

That works however I found that you ended up having to do a little more work to sanitize the filename that Django would have done for you. I guess if you customize the path then you should know how to customize the filename. Just seems like it violates DRY a little in that I shouldn't have to mess with the filename if I don't need to (Django should sanitize it like normal unless I tell it not to).  Just my opinion.

UPDATE: I had to get this working so I went back to it a couple weeks ago and realized that I could just use os to sanitize the filename. However I'm still sure there is a better way.

def get_path(instance, filename):
    return os.path.join(settings.MEDIA_ROOT, 'something', \
           instance.slug, filename)