Django on Shared Hostings

I spent last night setting up django a cgi enabled shared hosting. I faced some problems during this process and I decided to write a how to about “django on shared hosting”.

First of all, make sure your editor supports Unix file format. It took my whole night to determine why I was getting internal server error. I tried some free editor on windows and it seems Komodo Edit is the best one.

Second, make sure your hosting supports python, to test it you can use this script below. Don’t forget to change file permissions (755 is fine) to run it.
print "Content-type: text/html"
print "<pre>"
import os, sys
from cgi import escape
print "<strong>Python %s</strong>" % sys.version
keys = os.environ.keys()
for k in keys:
print "%st%s" % (escape(k), escape(os.environ[k]))
print "</pre>"

Now, prepare two folders to store your python lib and django projects, in your hosting something like /home/username/python and /home/username/projects, then get django and flup unzip and upload these libraries to python folder and upload your site to projects folder. Don’t forget to change permissions of your project to 755.

Almost done, a script is need to handle request;
import sys, os
sys.path += ["/home/username/python"]
sys.path += ["/home/username/projects "]
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")

You may need to place this script under the cgi-bin(or cgi) director. Some hosting providers don’t support fastcgi to run everywhere.

Now, modify and place following lines to your .htaccess file. mysite.cgi is the script above.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ cgi/mysite.cgi/$1 [QSA,L]

Done, call your domain, you will have django welcome message.