Monday, January 5, 2015

Set up Django on shared hosting environment - Hostgator

Before setting up Django on Hostgator, ensure you have access to shell. Hostgator grants jailed shell access.

1. Create a virtual environment, activate

Hostgator provides multiple versions of virtualenv. Check and use latest available version. Being a shared hosting, we do not have permissions to global install packages. We will have to live with packages provided.

Create virtual environment with --system-site-packages option to make use of system python packages eg. mysql-python

# Create virtual environments directory
cd ~
mkdir -p virtualenvs

cd virtualenvs

# Create virtual environement
/opt/python27/bin/virtualenv-2.7 --system-site-packages myenv


# Activate the virtual environment
source ~/virtualenvs/myenv/bin/activate


2. Create Django project

Hostgator provides an older version of Django

pip freeze | grep Django 
#Django==1.3.1


Install latest version of Django.

#Install Django 1.7
pip install Django==1.7



Follow Django tutorial to create a project.
cd ~
django-admin.py startproject mysite

Open settings file and modify as required.
vim ~/mysite/mysite/settings.py

# Modify database settings, to use mysql
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'user_testdb',
        'USER': 'user_testdbuser',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

# Add static root to server static files in the settings.py
STATIC_ROOT = '/home/user/www/static/'

3. Change .htaccess file

AddHandler fcgid-script .fcgi

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]

4. Point fcgi to your project

Put following content in index.fcgi
#!/home/user/virtualenvs/myenv/bin/python
import sys, os, user

# # Add a custom Python path.
sys.path.insert(0, "/home/user/virtualenvs/vaakya/bin/python")
sys.path.insert(0, "/home/user/mysite")
sys.path.insert(0, "/home/user/mysite/mysite")

# Switch to the directory of your project.
os.chdir("/home/user/mysite")

# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings"

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

5. Generate static file in the configured folder

cd ~/mysite/
python manage.py collectstatic

Done !!