I don't really blog anymore. Click here to go to my main website.

muhuk's blog

Nature, to Be Commanded, Must Be Obeyed

November 26, 2011

Working with files in Django - Part 2

First part of this article is here.

How to setup file serving for development server

As I mentioned earlier, it is best to serve files on a fast HTTP server. But this setup is overkill for development environments, you can safely let Django handle your files. The snippet below relies on the assumption, behind the scenes, that DEBUG is always True in development environment and it is always False in production environment. It should be fine for the purposes of this post:

from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()

It is quite straightforward. Nothing gets added to urlpatterns unless DEBUG is True and prefix (MEDIA_URL and STATIC_URL) is not a fully qualified URL.

How to reference STATIC files in templates

There are two ways to reference any file. You can use a file’s location in your file storage (your filesystem for example) for internal use. Or you can build a URL for the file so that clients can access it. This post will cover the latter, as the former is a simple matter of applying os.path.join() to STATIC_ROOT and the particular file’s path.

To build a URL in your templates you can simply concetenate STATIC_URL with the file’s relative location to it:

<img src="{{ STATIC_URL }}myapp/img/logo.png" />

However, to have STATIC_URL available within your template context you need to make sure of two things:

  • The template needs to be rendered with a RequestContext.
  • django.core.context_processors.static needs to be included in TEMPLATE_CONTEXT_PROCESSORS setting.

I can’t think of a reason why, but if for some reason you are not using RequestContext, you can provide STATIC_URL using get_static_prefix tag:

{% load static %}
{% get_static_prefix as STATIC_URL %}

<img src="{{ STATIC_URL }}myapp/img/logo.png" />

How to reference MEDIA files in templates

Dealing with MEDIA files is much simpler. The FieldFile object returned by ImageField and FileField has path and url properties and you don’t need to do concetenation yourself:

<img src="{{ some_model.some_image_field.url }}" />

Next part deals with adding files to your project.

If you have any questions, suggestions or corrections feel free to drop me a line.