Django

From DreamHost
Jump to: navigation, search

Overview

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.

Note2 icon.png Note: As of April 2015, DreamHost currently rims 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/Python apps only) is checked.
    Note2 icon.png Note: Enabling passenger forces your webdirectory to add the /public folder. Once you save your changes in the next step, all files in the current web directory will be moved to this new /public folder.


  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

  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 django-setup.py to your directory:
    wget http://wiki.dreamhost.com/django-setup.py
  4. Run the following command:
     python django-setup.py

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:~/example.com$ python django-setup.py
Looks like your domain is probably example.com ... 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: https://panel.dreamhost.com/index.cgi?tree=goodies.mysql
MySQL hostname: mysql.example.com Database name: mydatabasename MySQL username: mymysqlusername and password: ******* Checking connection... looks good! Creating project framework... creating passenger_wsgi.py... customizing settings... setting permissions... copying admin media... OK Running manage.py 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: user@example.com Password: Password (again): Superuser created successfully.
Installing custom SQL ... Installing indexes ... No fixtures found. Creating a Django superuser... Username: yourusername E-mail address: user@example.com 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 passenger_wsgi.py file is also created.

Important icon.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/django-admin.py", "django-admin.py", "startproject", projname) != 0:


Installing a custom Python version

Note2 icon.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 python.org. 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
    wget http://www.python.org/ftp/python/2.7.7/Python-2.7.7.tgz
    tar zxvf Python-2.7.7.tgz
    cd Python-2.7.7
    ./configure --prefix=$HOME/opt/python-2.7.7
    make
    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:
    /home/username/opt/python-2.7.7/bin/python
    
    Note2 icon.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. 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 get-pip.py file to your /tmp directory:
    curl https://bootstrap.pypa.io/get-pip.py > ~/tmp/get-pip.py
  3. Run the following command to install pip:
    python ~/tmp/get-pip.py

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:
    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/domainname/env/bin/activate
    
    • The name of the current virtual environment now appears on the left of the prompt. For example, (env)servername:your_project UserName$ 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
    
    Note2 icon.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/example.com/env).


Creating your Django project in virtualenv

  1. Run the following commands in order:
    cd $HOME/example.com
    source $HOME/domainname/env/bin/activate
    python env/bin/django-admin.py startproject <projectname>
    
    Note2 icon.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 passenger_wsgi.py file within your site's top level directory (/home/username/domain). If you followed the directions above to install Django, this file already exists and should contain the following:
    import sys, os
    sys.path.append(os.getcwd())
    os.environ['DJANGO_SETTINGS_MODULE'] = "djangotest.settings"
    import django.core.handlers.wsgi
    application = django.core.handlers.wsgi.WSGIHandler()
    
    • Be sure to replace the third line's projectname with your actual project name.
  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 setting file, found at example.com/projectname/settings.py 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/'
    • Make sure to create this /static directory on the server.
    • 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:
    https://docs.djangoproject.com/en/1.8/howto/static-files/
  4. Run the collectstatic command to set up the static items for the admin interface:
    cd $HOME/example.com
    projectname/manage.py collectstatic
    
  5. Set up your database as required within the settings.py file.
    • 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, run a syncdb:
    projectname/manage.py syncdb
    • Set up a superuser as required.

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

Troubleshooting

  • If your application isn't working, make sure you’re using the correct usernames, passwords, database names, and hostnames in the /projectname/settings.py 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 ~/example.com/tmp/restart.txt:
touch /home/user/example.com/tmp/restart.txt
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:
touch passenger_wsgi.py
  • If you installed a custom version of Python in your directory and you'd like to use it, add the following to your passenger_wsgi.py 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 passenger_wsgi.py and add the following:
sys.path.append(os.getcwd()+"/<project_name>")

See also