Monday, April 30, 2012

Python 2.7 + Django 1.4 on Bluehost

Bluehost is a cheap shared hosting provider, that allows to run applications using fastCGI, among others, webapps created with django - python web framework. In this post you will find information how to install the newest (in April 2012) versions of python and django and how to configure them for  bluehost.

First you need to enable ssh access to your bluehost account. Sign in to their control panel, enter Security > SSH/Shell Access and click Manage SSH Access button. Select SSH Access enabled and submit. Now connect via ssh to your bluehost account.

Python

Download, extract and install python 2.7 in your home directory:
mkdir python27
wget http://www.python.org/ftp/python/2.7.2/Python-2.7.2.tgz
tar xzvf Python-2.7.2.tgz
cd Python-2.7.2
./configure -prefix=/homeX/your_username/python27 --enable-unicode=ucs4
make
make install


Rename the python binary (to avoid overriding current system python version - if you're not using default bluehost python for anything else you can skip this step):
mv ~/python27/bin/python ~/python27/bin/python27
Add new python directory with binaries to your PATH environment variable. To do this edit .bashrc file in your HOME directory, for example with vim:
vim ~/.bashrc
and add the line at the end of the .bashrc file:
PATH=/homeX/your_username/python27/bin:$PATH
load the new settings:
source .bashrc
and then test it:
python27
You should see something similar to:
Python 2.7.2 (default, Apr 11 2012, 01:29:09)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

New python is available for you. Remember to use command python27 instead of python from now on.

Pip

We're going to use pip here - easy to use python package manager. It requires setuptools before it can be installed:

wget http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz
tar xzvf setuptools-0.6c11.tar.gz
cd setuptools-0.6c11
python27 setup.py install
cd
wget http://pypi.python.org/packages/source/p/pip/pip-1.1.tar.gz
tar xzvf pip-1.1.tar.gz
cd pip-1.1
python27 setup.py install


Now thanks to our earlier PATH settings pip is available from command line.

Django installation

With pip you can install latest stable Django (in my case 1.4) simply by entering:
pip install Django
Wait for download and installation process to complete. After that django is installed and command django-admin.py available. You will also probably need python driver for mysql database. Install it with pip:
pip install MySQL-python
If you're going to use PosgreSQL install psycopg2 library:
pip install psycopg2

Django configuration

Create django project:
django-admin.py startproject myproject

Decide what url should be used to access your django app. In my case it will be subdirectory:
http://somedomain.com/myproject

Prepare directory in bluehost public_html:
mkdir public_html/myproject
cd public_html/myproject


In this directory create fastcgi file (for example: mysite.fcgi) with content:
#!/homeX/your_username/python27/bin/python27
import sys, os

# Add a custom Python path.
sys.path.insert(0, "/homeX/your_username/python27")
sys.path.insert(13, "/homeX/your_username/myproject")

os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

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

Remember to change /homeX/your_username to your home directory path on bluehost. Change myproject.settings to correct project name. The first line contains path to your custom python binary.

Django fastcgi requires flup so install it with pip:
pip install flup
Also change file permissions to mysite.fcgi:
chmod 0755 mysite.fcgi

Now create .htaccess file in the public_html/myproject directory with content:
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]


That's all. You should see your django start page on: http://somedomain.com/myproject. You can start coding some real stuff in django now. Remember to install every python and django packages using pip - that way they will be available to your django app. Also keep in mind that every django commands like syncdb, collectstatic  etc. should be run using python27 for example:
python27 manage.py syncdb


***

Helpful materials, that I consulted during this installation and writing of this post:
Install Python 2.7 on BlueHost | Simply Me
2011 Installation Instructions for Django on Bluehost »

43 comments:

  1. Great tutorial es very helpful, but I can´t get css fiels from site admin, it return an 404 error. u.u

    ReplyDelete
    Replies
    1. Hi Eduardo,
      You need to configure the paths and urls to admin static files (this includes css) in your app's settings.py using STATIC_ROOT and STATIC_URL (you can read about this here ). STATIC_ROOT points to the path where your static files will be stored, for example:

      STATIC_ROOT = '/home/myusername/public_html/my_static'

      This settings is read by 'collectstatic' command that should be used to manage static files. It copies files from the static directiories inside django apps to the one pointed by STATIC_ROOT.

      STATIC_URL should point to the url where static files are visible for example if public_html directory from the above path is visible under: http://example.com url, then you will use something like:

      STATIC_URL = 'http://example.com/my_static'

      Now from django version 1.4 the static files for admin are expected to be found in STATIC_ROOT in admin. This is were collectstatic command will put them. So in your my_static dir there will be admin dir and in it the css dir with your admin's css files.

      For older versions of django the ADMIN_MEDIA_PREFIX needed to be set in settings.py. In that case you would add something like that:
      ADMIN_MEDIA_PREFIX = 'http://example.com/my_static/admin'

      Delete
    2. Thanks man. That saved hours of research.

      Delete
  2. Gotta say, this was the best guide I've read for installing Django on Bluehost! Using pip was the best idea! I tried setting this up last year, with a ton of different tutorials and it took days to get it up and running. Got this up in like 30 minutes! Thanks a bunch!

    ReplyDelete
  3. Excellent instructions, thank you!

    I got hung for a while (even though your instructions are correct/perfect), and the following helped me find my bug: https://my.bluehost.com/cgi/help/585

    In case it helps anyone else, my errors were:

    1. I didn't create the Django project in the right directory. Make sure you're in the directory you want the project to be in when you create the project. And make sure this path is added to the system path correctly in mysite.fcgi

    2. To fix the above error, I made a new Django project. However, in laziness, I copied the mysite.fcgi and .htaccess files from the old project. ** I forgot to change the package name in the RewriteRule to the new name ** This took me a couple hours to diagnose.

    ReplyDelete
  4. Thanks for putting these details up, you've saved me a lot of time. I had the same problem with the CSS on the admin site, but just created a symlink from the admin static directory inside the site-packages directory into my applications static directory and that fixed it up. Probably not the correct way to do it, but worked for me.

    ReplyDelete
  5. Great Tutorial. I've been messing with the .fcgi script and the .htaccess file for months off and on. Now it finally works.

    ReplyDelete
  6. Wow, this is a great article! As someone with little experience manually configuring a server, this was immensely helpful. It's awesome to see something other than PHP running on Bluehost!

    ReplyDelete
  7. I used this tutorial to install Django on Bluehost back in August. Worked great. Today, Bluehost decided to upgrade the MySql server on my box. Broke my Django install.

    I was able to get it back by logging into the SSH and typing:

    pip install MySQL-python --upgrade

    Hope this helps someone.

    ReplyDelete
  8. Is there anything different if I like to run django on multiple virtual hosts in bluehost?

    ReplyDelete
  9. Hey this is a GREAT tutorial.

    I am MUCH further along than I got on my own last year. THe only problem is that I am not getting a 500 Internal Server Error any ideas?

    ReplyDelete
    Replies
    1. 500 internal server error means only that your application throws some error. You need to check your error log in the bluehost panel to see more specific error message and this hopefully points you to a solution.

      Delete
  10. seriously excellent tutorial. thank you so, so very much!

    ReplyDelete
  11. This made my day. It's rare I follow the instructions in a tutorial and it works. Usually I have to muck with stuff. This saved me so much time.

    ReplyDelete
  12. Thank you kindly for this. It was indispensable in getting my site up!

    ReplyDelete
  13. What if I don't want my website to be on a subdomain? I just want to go to myexamplesite.com and have that load my django site instead of having to do myexamplesite.com/subdomain. I tried moving the fastcgi file to my public_html file but it doesn't get automatically called.

    ReplyDelete
    Replies
    1. I got it to work. You have to move both the .fcgi file and the .htaccess file...

      Delete
  14. Thanks for the great post! Most of your things worked well. I had one problem with mysite.fcgi
    After everyting was installed, I was getting a blank page in the browser and the following in error log:
    [Wed Jan 30 14:25:47 2013] [warn] [client 213.111.98.77] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
    [Wed Jan 30 14:25:47 2013] [error] [client 213.111.98.77] Premature end of script headers: cozmic.fcgi
    [Wed Jan 30 14:25:47 2013] [error] [client 213.111.98.77] Premature end of script headers: 500.php

    I spent several hours trying to find a solution, and finally it turned out that the problem was that I created mysite.fcgi in windows and uploaded it in binary mode. I found a clue on this page - https://my.bluehost.com/cgi/help/585
    Then I created a new file, uploaded it in ASCII mode and everyting worked!!!

    ReplyDelete
  15. Great post! One thing to note is that if you don't rename your interpreter from python to python27 then you have to edit the first line of mysite.fcgi to change the path to the interpreter to point to python instead of python27.

    ReplyDelete
  16. I have followed your tutorial, but when I visit http://mydoamin.com/test_project/ I get following :

    [an error occurred while processing this directive]

    you can visit http://mycruzan.net/test_project/ or http://mycruzan.net/test_project/mysite/

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. Sorry about the above deleted posts^ had some issues but I fixed it!

    Good tutorials tho- hope I saw this earlier :P

    Worked for me! Thanks :)

    ReplyDelete
  20. Bookmarking this page.. Thanks so much!

    ReplyDelete
  21. I ran into this issue at "make install":

    Creating directory /homeX/myusername/python27/bin
    /usr/bin/install: cannot create directory '/homeX': Permission denied
    Creating directory /homeX/myusername/python27/lib
    /usr/bin/install: cannot create directory '/homeX': Permission denied
    make: *** [altbininstall] Error 1

    Any ideas? Many thanks!!

    ReplyDelete
    Replies
    1. /homeX/myusername is a placeholder - you need to change it to point to your actual home directory, for example:

      /home3/bumblebee/python27/bin

      Delete
  22. Followed everything (i'm using a subdirectory so public_html/subdirectory/ holds .htaccess and mysite.fcgi), I'm getting redirected to my main website's 404 page.
    Why is this happening (I think it must be an .htaccess problem because when I run the .fcgi via ssh it returns me Django's main page)

    ReplyDelete
    Replies
    1. fixed it, I wrote the wrong path on the .fcgi file, I should've written the path to the site-packages directory.

      p.s.
      Apache Logs are a MUST for debugging.

      Delete
  23. Hello.

    I followed every step except installing mysql and postgre. (Django 1.5.1 + Python 3.3) But I got 500 error when I access my url. Do you have any idea?

    ReplyDelete
  24. I solved my problem. Flup module for python3 has an import bug in it's code.

    ReplyDelete
    Replies
    1. I think that is not a bug, but specific python3.3 syntax incompatible part with python2.7.

      Delete
  25. I tried the tutotial but installing python in another folder, it was a mess and didn't work, how can I uninstall it to start again? Or should I just delete the folders?

    ReplyDelete
    Replies
    1. I tried again very carefully and it finally worked! I'm only having some trouble with static files since I don't want them to be inside public_html but it works if I leave the folder there :)
      THANK YOU!

      Delete
  26. I have a

    500 Server Error

    A misconfiguration on the server caused a hiccup. Check the server logs, fix the problem, then try again.

    What can be a problem? fcgi file? what should I put in homeX (home1, home2 ? where can i find this info)

    ReplyDelete
  27. If you’re a business owner, you will encounter the need to find a web hosting provider for hosting your website. It is essential to any business that they reach out to the public the best they can.1 Dollar Hosting

    ReplyDelete
  28. I have to run http://domain.com/myproject.fcgi/ to get the root ... how do I set it up to run http://domain.com/ to get the root? For example if I want to get to the admin, I have to do: http://domain.com/myproject.fcgi/admin to get there. I would prefer to do: http://domain.com/admin to get there.

    ReplyDelete
  29. Looks like I needed to have this in my .htaccess file:

    RewriteRule ^(.*)$ testproject1.fcgi/$1 [QSA,L]

    instead of:

    RewriteRule ^(.*)$testproject1.fcgi/$1 [QSA,L]

    For some reason I didn't include a space between $ and testproject1.fcgi.

    ReplyDelete
  30. A mixed success so far. When I go to the url, I get a django 404 error. So... it is outputting something, but it isn't the start page.

    You got me a heck of a lot further than I've made it before, though.

    ReplyDelete
    Replies
    1. More here-- got to my admin pages, but none of them have CSS. I'm fairly new to web development, don't know what to do. StackOverflow seems to suggest my problem is in apache.

      Delete
  31. This comment has been removed by the author.

    ReplyDelete
  32. Thank you for the post! Your instructions are very clear and concise!

    I made a slight modification to your process by also using virtualenv for my website.

    For those interested, simply install 'virtualenv' with pip as soon as you install pip:

    1. Activate the virtualenv, and then install your modules like 'Django' and 'MySQL-python'.

    2. Follow the setups in the same fashion, replacing instances of the Python interpreter with the interpreter copied inside the virtualenv, e.g.:

    Instead of using the Python interpreter you just installed:

    /homeX/userX/python27/bin/python27

    Create a virtualenv and use that interpreter instead:

    /homeX/userX/all-virtualenvs-directory/mysite-virtualenv-directory/bin/python

    ReplyDelete
  33. Hello there,

    I am having a spot of trouble, I Follwed your guide for getting the CSS working however for some reason my admin page still isn't loading the CSS. I am working off of django 1.6 and have everything set up the best I can but for some reason the CSS won't load. I am working on a Bluehost apache2 server.

    ReplyDelete