From DreamHost
Jump to: navigation, search


Django is a web development framework for Python in the same way Rails is a framework for Ruby. It is used by a number of major web sites, including Google (i.e., for the Google Application Engine), and can make developing rich web applications much easier.

Django is not an application on its own. You will need proficiency in Python programming in order to write an application using Django.

Dh-kb-note-icon.fw.png Note: As of April 2015, DreamHost currently runs Django v1.3.1.

Setting up your user, domain, and database

Below are instructions for setting up Django using Passenger. Instructions for completing a FastCGI setup are still available at Django FastCGI, but are not recommended because FastCGI is significantly slower, and requires a more complicated configuration process. Django is also able to run under CGI, which is even slower than FastCGI which is never recommended.

  1. View the Enabling Shell Access article to set your user as a Shell user.
  2. Navigate to (Panel > ‘Domains’ > ‘Manage Domains’).
  3. Click the Edit button to the right of the domain under the ‘Web Hosting’ column.
  4. Scroll down to the ‘Web Options’ section and make sure the checkbox titled ‘Passenger (Ruby/NodeJS/Python apps only) is checked.
    Dh-kb-note-icon.fw.png Note: Enabling passenger forces your web directory to add the /public folder. Once you save your changes in the next step, this /public folder will be your site's web directory. Move any files into it you wish to display online.

  5. Scroll down and click the blue Change settings button to save your new settings.
  6. Navigate to (Panel > ‘Goodies’ > ‘MySQL Databases’).
  7. Create a new blank database which will only be used for your Django app.
    • Visit the phpMyAdmin article for details on your hostname, username, and password.

Installing Django using virtualenv

Using virtualenv to install Django is recommended. This is because when you use virtualenv, you create an isolated environment with its own installation directories. This allows you to install a custom version of Python and its different packages which is not connected to the global installation on the server. This also solves the issue with permissions when installing software.

Installing a custom Python version

Dh-kb-note-icon.fw.png Note: As of April 2015, DreamHost currently runs Python v2.7.3.

To install a custom Python version, you must download the version from The following describes how to install Python 2.7.7:

  1. Log into your server via SSH, and then run the following commands one at a time:
    cd ~
    mkdir tmp
    cd tmp
    tar zxvf Python-2.7.7.tgz
    cd Python-2.7.7
    ./configure --prefix=$HOME/opt/python-2.7.7
    make install
    • These commands install your local version of python to /home/<username>/opt/python-2.7.7.
  2. Add the following line to the bottom of your .bashrc file:
    source .bash_profile
  3. To add a path in order to use the new version of Python over the system default, enter the following line to your .bash_profile file which is in your user's directory:
    export PATH=$HOME/opt/python-2.7.7/bin:$PATH
  4. Run the following command to update this file:
    . ~/.bash_profile
  5. Check which version of Python you're now using by entering the following command:
    which python
    It should respond with this:
    Dh-kb-note-icon.fw.png Note: If it responds with a path like /usr/bin/python, then the newly downloaded copy is not being used. Most often this is due to the .bash_profile not being updated correctly. Try logging out and back in again. If necessary, repeat the steps above.

Installing pip

In order to install various python packages, and Django in particular, you will need pip. You may find it is already available since Python 2.7.9 and later (for Python 2) and Python 3.4 and later (for Python 3) now include it by default. To find out:

  1. Log into your server via SSH.
  2. Check to see if pip exists.
    $ which pip

If a path is listed, such as /usr/bin/pip, you are able to use pip to install virtualenv.

If it's not installed, proceed with the following steps:

  1. Log into your server via SSH.
  2. Run the following command to download the file to your /tmp directory:
    curl > ~/tmp/
  3. Run the following command to install pip:
    python ~/tmp/

Install virtualenv using pip

In order to "freeze" the package versions for your website (so they don't automatically update when you set up another site at a later date), install virtualenv:

pip install virtualenv

Setting up your Django site in virtualenv

  1. Run the following command to set up a new virtualenv within your domain’s directory. Make sure to replace <domain> with your domain name:
    virtualenv $HOME/<domain>/env
    • This creates a local copy of your environment specific to this website.
  2. To activate the local environment in order to make sure you're working with the right versions of your tools and packages while working on this website, run the following command:
    source $HOME/<domain>/env/bin/activate
    • Replace <domain> with your domain name.
    • The name of the current virtual environment now appears on the left of the prompt. For example, (env)[servername]$ to let you know that it’s active.
    • If you now run ‘which python’, you’ll see it’s using the virtualenv install of python which is in the domain’s /env folder.
    • From now on, any package that you install using pip will be placed in the env folder, isolated from the global Python installation.
    • You can then install packages as usual. For example:
    $ pip install requests
  3. Install a custom version of Django and any other required packages (e.g., MySQL-Python if you're going to use a MySQL database) for your website using pip:
    pip install Django
    pip install MySQL-python
    Dh-kb-note-icon.fw.png Note: If you are finished working in the virtual environment for the moment, you can deactivate it by running the following:
    $ deactivate
    • This puts you back to the system’s default Python interpreter with all of its installed libraries.
    • To delete a virtual environment, just delete /env folder. (In this case, it would be rm -rf /home/username/

Creating your Django project in virtualenv

  1. Run the following commands in order:
    cd $HOME/
    source $HOME/example/env/bin/activate
    python env/bin/ startproject <projectname>
    • Replace 'example' with your domain name.
    Dh-kb-note-icon.fw.png Note: When you run the 'startproject' command, it creates a new folder in your site directory named whatever your project name is.

  2. In order for Passenger to pick up your project, create a file within your site's top level directory (/home/username/domain). Add the following:
    import sys, os
    INTERP = "/home/<username>/local/bin/python"
    #INTERP is present twice so that the new python interpreter knows the actual executable path
    if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
    cwd = os.getcwd()
    sys.path.append(cwd + '/projectname')  #You must add your project here
    os.environ['DJANGO_SETTINGS_MODULE'] = "projectname.settings"
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()
    Dh-kb-note-icon.fw.png Note: Be sure to replace the following:
    • The path to your local python version in line #2. This will be something like /home/username/opt/python-2.7.7/bin/python.
    • The two instances of 'projectname' with your actual project name in lines 8 and 14.

  3. Set up Django's static file settings in order to correctly serve images, CSS, and JavaScript as you will need this for the admin interface to work. For example:
    • Within the projects file, found at you will find that the STATIC_URL is probably configured to /static/.
    • Add another line to set the location on the server of the actual static directory:
    STATIC_ROOT = os.path.dirname(BASE_DIR) + '/public/static/'
  4. In your /home/username/ directory, make sure to create this /static directory.
    • This will be the location where Django will put all of your static files – you shouldn't put stuff here manually as it gets overwritten. View the following link for further details:
  5. Run the collectstatic command to set up the static items for the admin interface:
    cd $HOME/
    python collectstatic
  6. Set up your database as required within the file. The section of the file originally looks like this:
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    Edit to make the following additions:
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'mydatabase',
            'USER': 'mydatabaseuser',
            'PASSWORD': 'mypassword',
            'HOST': '',
            'PORT': '3306',
    • The default is to use sqlite3, which may be suitable for the smallest of sites, but it's likely you'll want to set up a mysql database.
    • Once configured, navigate to the $HOME/<domain>/<projectname> directory where the file is located. Run the migrate command in your project directory:
    python migrate
    Operations to perform:
      Apply all migrations: admin, contenttypes, auth, sessions
    Running migrations:
      Rendering model states... DONE
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying admin.0002_logentry_remove_auto_add... OK
      Applying contenttypes.0002_remove_content_type_name... OK
      Applying auth.0002_alter_permission_name_max_length... OK
      Applying auth.0003_alter_user_email_max_length... OK
      Applying auth.0004_alter_user_username_opts... OK
      Applying auth.0005_alter_user_last_login_null... OK
      Applying auth.0006_require_contenttypes_0002... OK
      Applying auth.0007_alter_validators_add_error_messages... OK
      Applying sessions.0001_initial... OK

    You must now manually create your admin user. Run the following command:

    python createsuperuser

    You're prompted to create a username, password and email address.

    You should now see the standard Django holding page at your domain and be able to access the admin console at /admin/.

    Installing Django manually

    1. Log into your server via SSH with your Shell username.
    2. Make sure you’re in your site’s application directory. This is NOT the /public directory.
    3. Run the following command in this directory.
      This downloads a file named to your directory:
    4. Run the following command:

    After you run the setup command, the following script leads you through rest of the the process of setting up your application. The sections in BOLD are required information that you must enter:

    user@servername:~/$ python
    Looks like your domain is probably ... cool.
    Testing domain service...  lookin' good
    What would you like to name your project?
    >> djangotest
    An excellent name!
    You'll need a database for your Django project. If you don't already have one ready, you can create one from the DreamHost Panel at:
    MySQL hostname: Database name: mydatabasename MySQL username: mymysqlusername and password: ******* Checking connection... looks good! Creating project framework... creating customizing settings... setting permissions... copying admin media... OK Running syncdb... Creating table django_admin_log Creating table auth_permission Creating table auth_group_permissions Creating table auth_group Creating table auth_user_user_permissions Creating table auth_user_groups Creating table auth_user Creating table auth_message Creating table django_content_type Creating table django_session Creating table django_site
    You just installed Django's auth system, which means you don't have any superusers defined.
    Would you like to create one now? (yes/no): yes Username (Leave blank to use 'yourusername'): E-mail address: Password: Password (again): Superuser created successfully.
    Installing custom SQL ... Installing indexes ... No fixtures found. Creating a Django superuser... Username: yourusername E-mail address: Password: Password (again): Superuser created successfully.
    SUCCESS! Your Django application is fully set up - enjoy!

    Once complete, a new folder is created within your app directory which has the same name as the one you used to name your project during installation. A file is also created with the following:

    import sys, os
    os.environ['DJANGO_SETTINGS_MODULE'] = "mydjangoprojectname.settings"
    import django.core.handlers.wsgi
    application = django.core.handlers.wsgi.WSGIHandler()
    Dh-kb-important-icon.fw.png Important: If you receive an error related to line 126 in the Python code, you can fix the script by appending ".py" to the OS call by changing line 126 to look like the following:
    if os.spawnl(os.P_WAIT, "/usr/bin/", "", "startproject", projname) != 0:

    Visit your site and you'll see a Django welcome page.


    • If your application isn't working, make sure you’re using the correct usernames, passwords, database names, and hostnames in the /projectname/ file.
    • If you make changes to the code, such as working through the official tutorials, and they don't seem to work, make sure to kill any existing Python processes and reload the page:
    pkill python
    • If you modified your application and your changes do not seem to be reflected, you may need to notify Passenger about your change by creating or modifying ~/
    touch /home/user/
    Passenger looks for this file and reloads the application when this file is modified.
    • If you're using shared hosting and your changes do not seem to be reflected, you can notify Passenger about your change by running the following command:
    • If you installed a custom version of Python in your directory and you'd like to use it, add the following to your file:
    if sys.hexversion < 0x2060000: os.execl("/path/to/your/copy/of/python2.7", "python2.7", *sys.argv)
    • If you're getting meaningless 500 pages even though you have DEBUG enabled in your Django app, you're probably running into a Passenger problem dealing with errors. View the 500 Errors with Passenger WSGI Workaround article for details.
    • If you're following the Django tutorial or migrating an existing project, you may get "Premature end of script headers" in your sites Error log. This may be due to the Passenger file not including your project directory in its path. One solution is to open and add the following:

    See also