Deploying Django

Learn how to setup and deploy a Django website on a shared host

Using runserver makes things very easy for development — but it's only intended for development on your local machine. Exposing your website to the public will require additional work. You'll want to use a production web server, such as Apache or Nginx. In this short guide, I'll show you how to deploy your Django application. Let's get started.

Deploying Django depends on what host you're running on. If you're on a shared host, chances are you'll have to use FastCGI — a program that connects your Django project to a web server. If you're on a VPS, you should use WSGI instead. This guide is for shared hosts only. Finally, if your web host has a control panel for installing Django applications — use that instead of following this guide.

Deploying with FastCGI

First, install Flup which is used so Django can talk to FastCGI. Be sure to use the latest version, at the time of this writing it's 1.0.2:

tar xzvf flup-1.0.2.tar.gz
cd flup-1.0.2
cp -r flup /path/to/python/site-packages

Inside your public web directory, you'll want to create script to initate the FastCGI thread:

cd ~/path/to/public
touch dispatch.fcgi
chmod 755 dispatch.fcgi
vim dispatch.fcgi

Pase this program:

import sys
import os

sys.path.insert(0, '/path/to/local/lib/python2.7/site-packages')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproj.settings'

from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")

Now running ./dispatch.fcgi should launch your Django application! The only thing left to do is redirect any web requests to your FastCGI process. You can do that using .htaccess. Just edit the file ~/path/to/public/.htaccess:

AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f           
RewriteRule ^(.*)$ dispatch.fcgi/$1 [QSA,L]

That's it! Now when you head to your website's address in a browser, you should see your Django application running.