How to get server-side static image URL in Django

True Story Follows

I was googling the above term and got 0 helpful results, so I’m blogging about it.

The Problem

When using Django, there are some really nice abstractions for saving static files to Amazon S3, using a {% static %} tag in your Django template, and then magically the Amazon URL’s get spit out as something like:


But, if you want to make an API endpoint that returns the image URL’s inside of a JSON blob, suddenly Django’s built-in features don’t seem so awesome. You could create a hack to render json data to a template, but that just seems silly.

The nice thing about Python is that given a quandary like this, and when The Google isn’t helping, you can always just read the source code.

The Solution

The solution is actually quite simple. If you settings look kind of like this:

STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

Then all you need to do is:

from storages.backends.s3boto import S3BotoStorage

amazon_image_url = S3BotoStorage().url("img/something.jpg")

The End