Configuring Django

Serving Django Static Media

For better performance and resource allocation, configure a separate application to serve your Django application’s static media, such as images and stylesheets. To create and configure an application to serve Django’s static media:

  1. Log in to the control panel.

  2. Add a static media application to the Django website.

    1. Click Domains / websites ‣ Websites. The list of websites appears.
    2. Click on the name of the website that serves your Django application.
    3. Click Add an application ‣ Create a new application. The Create a new web app form appears.
    4. In the Name field, enter a name for the static media application.
    5. In the App category menu, click to select Static.
    6. In the App type menu, click to select Static only (no .htaccess).
    7. In the URL field, enter /static.
    8. Click the Save button. The application is installed and added to website’s list of applications.
  3. Configure Django to store and use static media from a single location.

    1. Open /home/username/webapps/django_app/project/project/settings.py in a text editor, where

      • username is your username,
      • django_app is the name of your Django application, and
      • project is the name of your Django project (for example, myproject).
    2. Verify that the django.contrib.staticfiles app is listed in your project’s INSTALLED_APPS setting.

    3. Django will automatically include your INSTALLED_APPS‘s static files (for example, the files in someapp/static and the Django admin media), but to include additional directories of static files, set STATICFILES_DIRS to a tuple of directory paths. For example:

      STATICFILES_DIRS = (
          '/path/to/static/files/',
          '/path/to/other/static/files/',
      )
      
    4. Set STATIC_URL to 'http://domain/static/' where domain is the domain name for your Django site.

    5. Set STATIC_ROOT to '/home/username/webapps/static_media_app/' where static_media_app is the name of the static media application.

    6. Save and close the file.

  4. Collect the static media into the static media application.

    1. Open an SSH session to your account.
    2. Switch to the Django project directory. Enter cd /home/username/webapps/django_app/project/ and press Enter.
    3. Enter pythonX.Y manage.py collectstatic, where X.Y is the version of Python for your Django application, and press Enter. The static files are copied to your static media application.
  5. Restart the Django application.

Configuring Django’s ALLOWED_HOSTS

As a security measure, Django validates host site’s host name when debug mode is disabled. Django will only respond to requests for the host names specified in the ALLOWED_HOSTS list.

To configure ALLOWED_HOSTS:

  1. Open your Django project’s settings file. For example, if you’re using the default project, then open ~/webapps/django_app/myproject/myproject/settings.py, where django_app is the name of your Django application as it appears in the control panel, in a text editor.

  2. Add the host names to serve to the ALLOWED_HOSTS list.

    For example, if your Django application is part of a website record that’s serving the domains mysite.example and www.mysite.example, then the ALLOWED_HOSTS setting would look like this:

    ALLOWED_HOSTS = [
        'mysite.example',
        'www.mysite.example',
    ]
    

    Alternatively, you can specify a subdomain wild card with a leading period. For example, to permit any subdomain of mysite.example, then the ALLOWED_HOSTS setting would look like this:

    ALLOWED_HOSTS = [
        '.mysite.example',
    ]
    

    See also

    See the official Django documentation for ALLOWED_HOSTS.

  3. Save and close the file.

  4. Restart the Django application.

Django now responds to requests for the specified domains. Requests for other domains raise a SuspiciousOperation exception.

Configuring Django to Use Memcached

See also

Memcached

To configure Django to use Memcached as Django’s cache backend, you must set the CACHES setting in settings.py. To set CACHES:

  1. Open an SSH session to your account.

  2. Install python-memcached for your Django application. Enter PYTHONPATH=$HOME/webapps/django_app/lib/python2.7/ easy_install-2.7 --install-dir=$HOME/webapps/django_app/lib/python2.7/ --script-dir=$HOME/webapps/django_app/bin/ python-memcached, where django_app is the name of the Django application as it appears on the WebFaction control panel, and press Enter.

  3. Open $HOME/webapps/django_app/project/project/settings.py in a text editor, where project is the name of the Django project.

  4. Add the CACHES setting. Append these lines:

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': 'unix:<MEMCACHED_SOCKET>',
        }
    }
    

    where <MEMCACHED_SOCKET> is the path to your memcached socket file (for example, /home/username/memcached.sock).

  5. Save and close the file.

  6. Restart the Django application.

Configuring Django to Send Mail

To configure Django to send mail through WebFaction’s SMTP server:

  1. Open an SSH session to your account.

  2. Open $HOME/webapps/django_app/project/project/settings.py in a text editor, where django_app is the name of the Django application as it appears on the WebFaction control panel and project is the name of the Django project.

  3. Add these lines:

    EMAIL_HOST = 'smtp.webfaction.com'
    EMAIL_HOST_USER = '<mailbox>'
    EMAIL_HOST_PASSWORD = '<password>'
    DEFAULT_FROM_EMAIL = '<address>'
    SERVER_EMAIL = '<address>'
    

    where

    • <mailbox> is the name of a WebFaction mailbox as it appears on the control panel,
    • <password> is the mailbox password,
    • and <address> are email addresses configured on the WebFaction control panel.
  4. Save and close the file.

  5. Restart the Django application.

Configuring Django’s Time Zone

WebFaction servers are configured to use UTC as the local time zone, but each Django installation has its own time zone configuration.

For Django 1.4 and newer, Django can be configured to use datetimes that are aware of time zones. To use time zone-aware datetimes, set USE_TZ = True in your Django application’s settings module.

For earlier versions of Django, set TIME_ZONE to a valid time zone name in your Django application’s settings module.

For more information about time zone configuration, including valid time zone names and alternative configurations, see TIME_ZONE in the Django project documentation.

Mounting a Django Application on a Subpath

A Django application mounted on a path other than the root of a domain must set the FORCE_SCRIPT_NAME setting. If FORCE_SCRIPT_NAME is not set, Django URLs will not be directed correctly. This may cause bad links, 404 Not Found errors, and There is no application mounted at the root of this domain errors.

To add the FORCE_SCRIPT_NAME setting:

  1. Open an SSH session.
  2. Open $HOME/webapps/django_app/project/project/settings.py in a text editor, where
    • django_app is the name of the Django application as it appears in the WebFaction control panel,
    • and project is the name of the Django project (typically myproject).
  3. Add FORCE_SCRIPT_NAME = 'path', where path is the path on the domain where the application is mounted. For example, if the Django application were mounted on example.com/blog, settings.py would contain FORCE_SCRIPT_NAME = '/blog'. Do not use a trailing slash.
  4. Save and close the file.
  5. Restart the Django application.

Once the server has restarted, Django will properly handle URLs on the selected domain path.

Password Protecting a Django Application

You can provide simple password protection for a Django application by configuring the application’s Apache server to use basic access authorization.

  1. Create an htpasswd file to store permitted usernames and passwords.

    1. Open an SSH session to your account.
    2. Switch to the directory of the Django application. Enter cd $HOME/webapps/django_app where django_app is the name of the Django application as it appears in the control panel, and press Enter.
    3. Create the htpasswd file. Enter htpasswd -c htpasswd username where username is the first username you wish to create, and press Enter. A prompt appears to enter a new password.
    4. At the prompt, enter a new password and press Enter. Another prompt appears to confirm the password. Reenter the password and press Enter.
  2. Configure the Django application’s Apache web server to permit access only to users specified in the htpasswd file.

    1. Open $HOME/django_app/apache2/conf/httpd.conf in a text editor.

    2. Near the top of the file, find a series of LoadModule directives. Add these three additional directives:

      LoadModule auth_basic_module modules/mod_auth_basic.so
      LoadModule authn_file_module modules/mod_authn_file.so
      LoadModule authz_user_module modules/mod_authz_user.so
      
    3. At the end of the file, add these lines:

      <Location "/">
          AuthType Basic
          AuthName "My Password Protected Area"
          AuthUserFile /home/<username>/webapps/<django_app>/htpasswd
          Require valid-user
      </Location>
      

      where <username> is the account name and <django_app> is the name of the Django application as it appears in the control panel.

      You may also change the string following AuthName with the text of your choice or change the path in <Location "/"> to a more specific subpath (for example, <Location "/private">).

    4. Save and close the file.

  3. Restart the Django application.

The Django application (or specified subpath) is now password protected. If needed, you may create and update usernames and passwords. From the application directory, enter htpasswd htpasswd username, where username is a new or existing username, and press Enter. A series of prompts appear to enter and confirm the password.

Restarting a Django Application

You can restart your Django application’s Apache server at any time. To restart the Apache instance and Django:

  1. Open an SSH session.

  2. Run the restart script for your Django application. Enter $HOME/webapps/django_app/apache2/bin/restart, where django_app is the name of the Django application, and press Enter. Your Django application restarts in a few seconds.

    Note

    Alternatively, you may manually start and stop the Apache instance. To stop the server, enter $HOME/webapps/django_app/apache2/bin/apache2/bin/stop and press Enter. To start the server, enter $HOME/webapps/django_app/apache2/bin/apache2/bin/start and press Enter.

Setting Up a Database

Note

Configuring a database changed considerably from Django 1.1 to Django 1.2. Please see the Django 1.2 release notes section Specifying databases and Django 1.1 Settings documentation for details.

To set up a database for a Django application:

  1. Optional: If you’re using a PostgreSQL or MySQL database, create a new database. Make a note of the database type, name, username, and password.

  2. Configure the database.

    1. Open an SSH session to your account.

    2. Open the Django application’s settings.py file in a text editor. By default, this file is found at $HOME/webapps/django_app/project/project/settings.py, where django_app is the name of the Django application as it appears on the control panel.

    3. Replace these lines:

      DATABASES = {
          'default': {
              'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
              'NAME': '',                      # Or path to database file if using sqlite3.
              'USER': '',                      # Not used with sqlite3.
              'PASSWORD': '',                  # Not used with sqlite3.
              'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
              'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
          }
      }
      

      with these:

      DATABASES = {
         'default': {
             'ENGINE': '<engine>',
             'NAME': '<db_name>',
             'USER': '<db_user>',
             'PASSWORD': '<db_password>',
             'HOST': '',
             'PORT': '',
         }
      }
      

      where:

      • <engine> is django.db.backends.postgresql_psycopg2 for PostgreSQL databases, django.db.backends.mysql for MySQL databases, or django.db.backends.sqlite3 for SQLite version 3 databases,
      • <db_name> is the path to the SQLite database file or the name of the MySQL or PostgreSQL database,
      • <db_user> is blank for SQLite databases or a username with permission to access the database, and
      • <db_password> is blank for SQLite databases or the password for the database user.
    4. Save and close the file.

  3. Synchronize the database.

    1. Switch to the Django project directory. Enter cd $HOME/webapps/django_app/project/ where project is the name of the project directory, and press Enter.
    2. Enter pythonX.Y manage.py syncdb, where X.Y is your Django application’s version of Python and press Enter.
  4. Restart the Django application.

Upgrading your Django Libraries

To upgrade the Django libraries used by your Django application:

  1. Open a SSH session to your account.

  2. Go to your Django application directory. Enter cd $HOME/webapps/app_name where app_name is the name of the Django app that you are upgrading.

  3. Download the Django source package. Enter wget https://www.djangoproject.com/m/releases/X.Y/Django-X.Y.Z.tar.gz where X.Y and X.Y.Z are version numbers (for example, 1.6 and 1.6.5), and press Enter. An archive file is created in the current directory.

    See also

    See the Django download page for additional downloads and links to release notes.

  4. Decompress the archive. Enter tar -zxvf Django-X.Y.Z.tar.gz and press Enter. A directory containing the contents of the archive is created.

  5. Rename your old Django libraries to move them out of the way. Enter mv lib/pythonA.B/django lib/pythonX.Y/django.old, where A.B is the Python version used with the Django application, and press Enter.

  6. Copy the new libraries into your Python library directory. Enter cp -R Django-X.Y.Z/django lib/pythonA.B and press Enter.

  7. Copy the new management scripts into $HOME/webapps/app_name/bin. Enter cp Django-X.Y.Z/django/bin/* bin and press Enter.

  8. Make any changes to your project code as directed by the release notes for the Django version you’re upgrading to.

  9. Restart the Django application.

  10. Delete the Django source archive and directory. Enter rm -rf Django-X.Y.Z* and press Enter.

  11. Delete your old Django libraries. Enter rm -rf lib/pythonA.B/django.old and press Enter.

Note

This will not change the Django version number shown in the control panel. The control panel only records originally installed version numbers.

Using the Latest Django Trunk

The WebFaction control panel includes an installer for the latest trunk version of Django. The installers use a nightly export of the trunk from the official Django repository. These installers allow you to run a recent version of Django quickly and easily. That said, the installers provide exports of the Django trunk, not a version-controlled checkout. To replace installed Django libraries with a Git clone of the Django repository:

  1. Open an SSH session to your account.

  2. Remove the existing Django libraries. Enter mv $HOME/webapps/app/lib/pythonX.Y/django $HOME/webapps/app/lib/pythonX.Y/django_original, where app is the name of the application and X.Y is the Python version used with the application, and press Enter.

  3. Clone the Django repository. Enter git clone https://github.com/django/django.git $HOME/django and press Enter. A clone of the Django repository is created in your home directory.

    Note

    You can put the Django repository anywhere you like. To use another directory, substitute $HOME/django with your preferred destination.

  4. Create a symbolic link to the Git repository’s Django library. Enter ln -s $HOME/django/django $HOME/webapps/app/lib/pythonX.Y/django and press Enter.

  5. Restart the Django application.

Now the Django application uses the version-controlled Django checkout.