Django: Setting up sub-domain to serve static files

In my last post, I discussed how to set up Django with Apache and mod_wsgi. In this post, I will discuss how to set up a sub-domain to serve static files (css, js, images, etc). The Django documentation states that using a sub-domain for static files is recommended.

Note: Although I set up my Django installation on Ubuntu, most of these instructions are common to most OS’s.

Create folder

First we will create a folder under our server root. I’ll name it media, but you can name it whatever you like.

sudo mkdir /srv/www/media

Adding Host Entries

Just like the previous posts, we must create a host entry.

sudo vi /etc/hosts

Now add the following to the end of the file:

10.211.55.8     media.staticfiles

Remember, if you do not know your ip address, run:

ifconfig

If you followed my previous post, your hosts file should look like the following (but with a different IP address):

10.211.55.8     djangoserver 
10.211.55.8     wsgi.djangoserver 
10.211.55.8     testsite.djangoserver 
10.211.55.8     media.staticfiles

Create Virtual Hosts

Next we will create a virtual host.

sudo nano /etc/apache2/sites-available/media

Add the following content and save:

<VirtualHost *:80> 
 
    ServerName media.staticfiles 
    DocumentRoot /srv/www/media 
 
    <Directory /srv/www/media> 
        Options Indexes FollowSymLinks MultiViews 
        AllowOverride All 
    </Directory> 
 
</VirtualHost>

Now we have to activate the site and restart apache:

sudo a2ensite media
sudo /etc/init.d/apache2 reload

Change Ownership

The ‘media’ folder is currently owned by root. We will change it so that it is owned by Apache.

cd /srv/www
sudo chown web-data media
sudo chgrp web-data media

Creating the Static files folder

Next, I need to create a folder to store my static files. Because I plan to create multiple Django sites, I will create a folder for each site and then create a ‘static’ folder under each.

cd media
sudo mkdir testsite
sudo mkdir testsite/static

Note: You will need to change the ownership of the folders to Apache.

Now copy all of your css, js, and image files under the static directory:

testsite/static/css
testsite/static/js
testsite/static/images

Django’s Settings file

Open your settings.py file and add the following to the STATIC URL setting:

?View Code PYTHON
STATIC URL = 'http://media.staticfiles/testsite/static/

That’s it. Now, when you use ‘STATIC URL’ in your templates, you will be serving static files from your sub-domain.

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" media="screen" />

Note: In order for your templates to understand the ‘STATIC URL’ setting, your view must pass the reference to your template. If you do not know how to do this, please read my next post, How to set up a Home page with Django. Enjoy.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks