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 »

80 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
    2. Hi Asaf, kinda late here but what do you mean by ur fix. what has the site-packages directory got to do here. I have the same 404 page issue and i cant understand how you fixed urs

      Delete
    3. I think he was saying he solved his problem when he realized the path in the .fcgi file needs to point to the correct site-packages directory.

      That would explain the difference between the behavior when running it via the shell. Using a path set up by virtualenv, for example, the environment could be completely different ie. different versions of python and/or packages.

      Delete
    4. @Mike Salem Thanks Mike. I have done that ( linked to the site packages in my python27 folder. I added another import line in the file "sys.path.insert(14, "/home/username/python27/lib/python2.7/site-packages")" but still i get a 404 page of my wordpress site that lives directrly in my public_html folder. The script seems to run from shell but the django page just does not show up when i visit my url and browse the project folder. Clueless now

      Delete
    5. When you run the fcgi file from the shell you should see the response text (presumably, your homepage). If you're not seeing that, I recommend his other piece of advice which is to look for errors in the server logs.

      Delete
    6. I do actually see a homepage (the django default html page) from the shell. It is when i visit the folder containing my fcgi file that i get a 404 error. I have a wordpress site in my primary folder so i created another folder to contain my fcgi file and its own .htaccess but when i go to this folder i get a 404 page of the wordpress site. but it works in the shell so...

      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. 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
  28. 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
  29. 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
    2. Mitchell - this is exactly my problem. Were you able to resolve this? If so how?
      Lee

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

    ReplyDelete
  31. 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
  32. 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
    Replies
    1. This comment has been removed by the author.

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

      Delete
    3. In the following link I found the solution to this problem

      http://stackoverflow.com/questions/21808593/django-1-6-admin-page-css-not-working-with-bluehost

      Delete
  33. Isn't "sys.path.insert(13, "/homeX/your_username/myproject")" inserting to an arbitrary point in the system path? Shouldn't it instead be 'sys.path.append("/homeX/your_username/myproject")'?

    ReplyDelete
  34. WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI!
    WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
    WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
    WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
    Status: 200 OK
    I am getting this error please help

    ReplyDelete
    Replies
    1. Those warnings are normal. You're getting response code 200 OK which indicates no error.

      Delete
  35. Thanks for the tutorial... it was quite helpful.

    I have a django project with many hard-coded urls (such as <a href = "/foo" />, or redirect('/foo'), etc.).

    I have deployed this on bluehost on a sub path /myproject. I can see the homepage on http://example.com/myproject. But when I click on a link or get redirected, it goes to http://example.com/foo (giving me a 404). Is there any way I can force all such links and redirects to go to http://example.com/myproject/foo instead?

    One way that could work would probably be to use the {% url %} tag in all my links and reverse() for my redirects, and set FORCE_SCRIPT_NAME = '/myproject' in settings.py. Is there any other possible way?

    TIA

    ReplyDelete
  36. Hi Akhilesh, I am not the owner of this blog nor writer of this post but I think what you're looking for is some Apache[?] setting in the project's .htaccess file. Maybe try the last/bottom two answers in this StackOverflow question https://stackoverflow.com/questions/2536985/django-urlconf-or-htaccess-trouble

    Hope it helps.

    ReplyDelete
  37. this is great. one thing to note though, the line with './configure' and '--enable', it actually wraps onto line next to it so they look like separate commands, but i don't think they are?

    ReplyDelete
  38. also, `source .bashrc` should be `source ~/.bashrc` since there's no `cd` in there before that?

    ReplyDelete
  39. and you also might want to add how to exit python27 after testing that `python27` works.

    ReplyDelete
  40. It's true Bluehost is the industry leading hosting provide and they are best For wordpress Hosting, I written an Bluehost wordpress Hosting review and The about Bluehost Discount coupon code. you can check my blog post.

    ReplyDelete
  41. Good review about Bluehost web hosting, I prefer Bluehost from any other hosting company,
    By the way i have written an article about the review of Bluehost wordpress hosting thanks

    ReplyDelete
  42. Hello, nice to meet you.
    Good to see your patient about bluehost hosting coupon.
    By the way , i also a fan of bluehost & recently published the article about their cost on different plans. so read read the review now. bluehost pricing review thanks

    ReplyDelete
  43. Exclusive Discount: BlueHost At $3.45/Mo
    Free ‘.com’ domain
    24/7 technical support
    WordPress integration
    Unlimited traffic
    30-day money-back guarantee
    BlueHost WEb Hosting

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

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

    ReplyDelete
  46. Its give me
    500 Server Error

    A misconfiguration on the server caused a hiccup. Check the server logs, fix the problem, then try again.
    URL: http://mydomain.com/myproject/


    please help me


    ReplyDelete
  47. This tutorial is very helpful. I've been trying to set it up and use Python on my BlueHostweb hosting account with no luck. Thanks for this tutorial, I've bookmarked it to try the tips and see how it works.

    I've been using BlueHost web hosting service over the past few years. And I'm pretty happy with the service quality. I'm using it for hosting a couple WordPress websites. The website speed and page loading speed is pretty nice with a nice performance.

    Furthermore, I've wrote an article comparing BlueHost web hosting plans and which one to choose for your website. Please check it out and let me know your feedback.

    ReplyDelete
  48. You'll also find that Rad Web Hosting offers Python/Django support and is an official sponsor of the Django Project: https://radwebhosting.com/about-us

    ReplyDelete
  49. Purchasing USA-based hosting for a site that is not legal to be run in America is not a sensible thing to do. offshore bitcoin vps can be helpful for less scrupulous businesses who wish to bypass local laws or regulations, particularly for issues like copyright law, which is also known as no DMCA hosting.

    But this doesn’t mean that you can host illegal content which is strictly forbidden I.e. Phishing, Spamming. Scamming, Carding, Fraudulent activities, Child Porn and material that supports Terrorism.

    ReplyDelete
  50. cheap dedicated server host your DMCA ignore projects with peace of mind. We do offer 2 different locations like Russia, Netherlands. Streaming servers are also available for Sporta streaming. You can order custom configuration for your dedicated servers.

    Our data centers are connected with 10+ Gbps of the Channel, which provides low latency as well as cheap prices.

    ReplyDelete
  51. you would not really want to deal with those rip-off travel agents”
    webcare360

    ReplyDelete
  52. Thanks for sharing such amazing content which is very helpful for us. Please keep sharing like this. Also check to learn Django Python Framework Course or many more.

    ReplyDelete