Serving Up Media Files

Introduction

To complete the steps on this page should take five minutes.

The correct way to have the static media files that Django CMS needs served up is with a server, such as Apache, that is designed to do this work. See

for more information.

However, for development or testing purposes only you can use Django itself to do this for you. Note that

warns quite clearly:

Using this method is inefficient and insecure. Do not use this in a production setting. Use this only for development.

MEDIA_ROOT - where we'll keep the static media files

Edit MEDIA_ROOT in settings.py. MEDIA_ROOT is where your static files live; it's an absolute path to the files. They can go anywhere, but a place outside your project is best. An example might be:

MEDIA_ROOT = '/home/django-user/media/'

Setting up a URL pattern for the static media files

Now we need to set up a URL pattern that will find those files when a browser makes an HTTP request for them. A suitable place to serve up the media files might be site_media_files, just as an example. Note: don't use media for this address - media is already used for core Django files, so you'll only confuse it if you do.

We will tell Django that we want it to ask for them at

http://<server address>:8000/site_media_files

For example, the URI of a CSS file banners.css might be

http://<server address>:8000/site_media_files/css/banners.css

and Django will serve up the file

/home/django-user/media/css/banners.css

To urls.py add:

from django.conf import settings
if settings.DEBUG:
    urlpatterns += patterns('',
	(r'^site_media_files/(?P<path>.*)$', 'django.views.static.serve',
	        {'document_root': settings.MEDIA_ROOT}),
)

This tells Django:

  • to import the variables we set in settings.py
  • then, only if we're running this as a development server:
  • add the following instructions to our existing urlpatterns:
  • if the URI contains site_media_files, serve the corresponding files found in the MEDIA_ROOT setting we entered earlier, using Django's static files server

You can easily test this. Place an image at

/home/django-user/media/test.jpg

on your server. You should be able to load it in a browser at:

http://<server address>:8000/site_media_files/test.jpg

Now, in settings.py, we need to set:

MEDIA_URL = '/site_media_files/'

Note that the leading and trailing slashes are important.

Serving up the admin interface media files

Finally, we need to make Django CMS's built-in media files, which contain JavaScript and CSS for the admin interface, available for serving.

These files are at:

<path-to-django-cms>/media/cms

but we're serving up the media files from MEDIA_ROOT. So either:

  • copy the <path-to-django-cms>/media/cms directory to your media files directory (/home/django-user/media in our example), or
  • create a symbolic link to it, named cms

Now the admin interface should look and behave like the demonstration installation at: