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 ‘Users, Files, and Paths’ section.
    You’ll see your domain’s web directory.
  5. If your web directory does not end with "/public", add that to the end of your web directory.
  6. Scroll down to the ‘Web Options’ section and make sure the checkbox titled ‘Passenger (Ruby/Python apps only) is checked.
  7. Scroll down and click the blue Change settings button to save your new settings. {{Note2|If you currently have files under the domain, you must move them into the new "/public" directory to make them appear.
  8. Navigate to (Panel > ‘Goodies’ > ‘MySQL Databases’).
  9. 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 index for admin.LogEntry model Installing index for auth.Permission model Installing index for auth.Group_permissions model Installing index for auth.User_user_permissions model Installing index for auth.User_groups model Installing index for auth.Message model 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:
    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
    
    • This command installs your local version of python to /home/<username>/opt/python-2.7.7.
  2. 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
    
  3. Run the following command to update this file:
    . ~/.bash_profile
    
  4. Check which version of Python you're now using by entering the following command:
    python -V
    
    It should respond with this:
    /home/username/opt/python-2.7.7/bin/python
    

Installing pip

In order to install various python packages, and Django in particular, you must install pip:

  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
  4. 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

  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 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

  1. Run the following commands:
    cd $HOME/example.com
    
    python env/bin/django-admin.py startproject <projectname>
    
  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
    cwd = os.getcwd()cd sys.path.append(cwd)
    sys.path.append(cwd + '/projectname')  #You must add your project here
    
    #Switch to new python
    if sys.version < "2.7.7": os.execl(cwd+"/env/bin/python", "python2.7", *sys.argv)
    
    sys.path.insert(0,cwd+'/env/bin')
    sys.path.insert(0,cwd+'/env/lib/python2.7/site-packages/django')
    sys.path.insert(0,cwd+'/env/lib/python2.7/site-packages')
    
    os.environ['DJANGO_SETTINGS_MODULE'] = "projectname.settings"
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()
    
    • Be sure to replace the two instances of 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/'
    • 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 settings 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