Django

Django is a popular web application framework built with Python. Opalstack provides a simple installer for Django with Python 3.10 served by uWSGI.

Installation

To install a Django application follow our general instructions for adding applications and select "Django" as the application type in step 5.

When the installation is complete, the following files and directories will be present in the application directory:

  • start and stop: scripts to control the operation of your application.
  • env: a directory containing the Python 3 environment used by your application.
  • tmp: a directory containing temporary files used by your application
  • myproject: a directory containing a demo Django project.
  • uwsgi.ini: the uWSGI configuration file for your Django application.

Post-installation steps

Please take the following steps before you begin to use your Django installation:

  1. Connect your Django application to a site in the dashboard.

  2. Edit the app's myproject/myproject/settings.py to set ALLOWED_HOSTS to include your site's domains.

    Example:

    ALLOWED_HOSTS = ['domain.com', 'www.domain.com']
    
  3. Run the following commands to restart your Django instance:

    /home/username/apps/appname/stop
    /home/username/apps/appname/start
    

Installing Python dependencies for your Django project

See Installing Python dependencies for your project in our uWSGI documentation.

Using Databases with Django

PostgreSQL

To use a PostgreSQL database with your Django project:

  1. Create a new PostgreSQL database and user and make a note of the following:

    • The database name
    • The database user name
    • The database user password
  2. SSH into your Django application's shell user account and run the following commands to install the PostgreSQL dependencies for Python (substituting myapp with your Django application name):

    source ~/apps/myapp/env/bin/activate
    pip install "psycopg[binary]"
    
  3. Configure DATABASES in your project's settings.py as follows:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'your_database_name',
            'USER': 'your_database_user_name',
            'PASSWORD': 'your_database_user_password',
            'HOST': '',
            'PORT': '',
        }
    }
    

MariaDB (MySQL)

Opalstack uses MariaDB for MySQL-compatible database services. To use a MariaDB database with your Django project:

  1. Create a new MariaDB database and user and make a note of the following:

    • The database name
    • The database user name
    • The database user password
  2. SSH into your Django application's shell user account and run the following commands to install the MariaDB dependencies for Python (substituting myapp with your Django application name):

    scl enable devtoolset-9 bash
    source ~/apps/myapp/env/bin/activate
    pip install mysqlclient
    
  3. Configure DATABASES in your project's settings.py as follows:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'your_database_name',
            'USER': 'your_database_user_name',
            'PASSWORD': 'your_database_user_password',
            'HOST': '',
            'PORT': '',
        }
    }
    

SQLite

For Django apps installed after December 2021

To use SQLite with Django apps installed via your Opalstack dashboard after December 2021 configure DATABASES in your project's settings.py as follows:

    # then configure the engine and path to the DB here
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

Prior to running Django management commands on a Django project that uses SQLite, you will need to execute the following command in your shell session to ensure that Django uses the correct version of SQLite:

    export LD_LIBRARY_PATH=/usr/sqlite330/lib

For Django apps installed prior to December 2021

To use a SQLite database with Django apps installed prior to December 2021 you will need to install an updated SQLite binary package for Python and configure Django to use it as shown below.

  1. SSH into your Django application's shell user account and run the following commands to install the PostgreSQL dependencies for Python (substituting myapp with your Django application name):

    source ~/apps/myapp/env/bin/activate
    pip install pysqlite3-binary
    
  2. Configure DATABASES in your project's settings.py as follows:

    # include the next 3 lines in your settings.py just before the DATABASES dict
    __import__('pysqlite3')
    import os
    import sys
    sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
    
    # then configure the engine and path to the DB here
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    

Serving your own Django project

To serve your own Django project from your installed Django application:

  1. Upload your Django project directory to the root of your application directory, for example /home/username/apps/appname. You can upload your project via SFTP or with commandline tools such as scp or rsync.

  2. Log in to a SSH session and activate the application's Python environment:

    cd ~/apps/appname
    source env/bin/activate
    
  3. Install your project's Python dependencies. See Installing Python Dependencies for your Django Project for more information.

  4. Edit /home/username/apps/appname/uwsgi.ini and set the python-path, wsgi-file, and touch-reload options (at the end of the file) to point at your project.

    For example, if your project name is "newsite":

    # adjust the following to point to your project
    python-path = /home/username/apps/appname/newsite
    wsgi-file = /home/username/apps/appname/newsite/newsite/wsgi.py
    touch-reload = {appdir}/newsite/newsite/wsgi.py
    
  5. Run the following commands to restart your Django instance:

    /home/username/apps/appname/stop
    sleep 2
    /home/username/apps/appname/start
    

Serving static content for your Django project

This procedure will configure your site to serve your Django applications static assets directly from Opalstack's frontend Nginx server via a separate static application. This configuration improves the overall performance of your application in a couple of ways:

  • Since your backend uWSGI server isn't servicing requests for static media, it's able to service dynamic requests more efficiently.
  • Nginx serves static content more efficiently than uWSGI, so your static content will load faster for your visitors.

To serve your project's static content:

  1. Create a "Nginx Static Only" application and make a note of the application name.

    The remainder of these steps will refer to the application as "mystatic".

  2. Edit your site to add a site route serving the mystatic application on the URI path /static.

  3. SSH into your app's server as the app's shell user.

  4. Edit your project's settings.py to set the following variables:

    STATIC_ROOT = '/home/username/apps/mystatic'
    STATIC_URL = '/static/'
    
  5. Go into your app directory and activate your Python environment:

    cd ~/apps/myapp
    source env/bin/activate
    
  6. Go into your project directory and run the collectstatic management command. This copies your app's static files into your static app directory.

    python manage.py collectstatic
    
  7. Run the following commands to restart your Django instance:

    /home/username/apps/appname/stop
    /home/username/apps/appname/start
    

Sending Email from Django

The following Django project settings should be used when you need to send email from your Django application via Opalstack's SMTP service:

DEFAULT_FROM_EMAIL = 'user@domain.com'
SERVER_EMAIL = 'user@domain.com'
EMAIL_HOST = 'smtp.us.opalstack.com'
## EMAIL_HOST = 'smtp.de.opalstack.com'
EMAIL_HOST_USER = 'mail_user_name'
EMAIL_HOST_PASSWORD = 'mail_user_password'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
## EMAIL_USE_SSL = True
## EMAIL_PORT = 465
  • DEFAULT_FROM_EMAIL and SERVER_EMAIL (and any address used to send mail from your application) must meet Opalstack's outgoing mail domain requirements.
  • EMAIL_HOST is the SMTP server. Use the US or DE version, whichever one your mailbox is on.
  • EMAIL_HOST_USER is the name of the Opalstack mailbox that you want to use to send your messages. Do not include the IMAP hostname in your username, use only the name like "bob", not "bob@imap1.us.opalstack.com".
  • EMAIL_HOST_PASSWORD is your mail user's password.
  • You must use either TLS or SSL encryption, as Opalstack SMTP does not accept unencrypted connections.
  • For TLS use EMAIL_USE_TLS = True and EMAIL_PORT = 587.
  • For SSL use EMAIL_USE_SSL = True and EMAIL_PORT = 465.
  • Do not configure both; use one or the other.
  • Django versions prior to 1.7 must use the TLS option and not the SSL option.

⚠️ Warning!

If you do not configure the encryption options as described above, then your application will hang and possibly crash when it attempts to send email.

Serving a Django app on a sub-path

The default uWSGI configuration created by our Django application installer works for Django applications running at the root of your domain - that is, the Django app is attached to your site route using / as the URI path.

If you need to run your application on a URI path below the root (aka a sub-path) then some minor changes to your application's uWSGI configuration are needed.

The following steps show how to serve a Django app named myapp (owned by shelluser) on a URI path /foo:

  1. If you've not done so already, edit your site to assign myapp to the URI path /foo.

  2. Locate your application's uwsgi.ini file. By default this file is created in the root of your application directory like /home/username/apps/myapp/uwsgi.ini.

  3. Open the uwsgi.ini file in your preferred editor.

  4. Change the wsgi-file configuration line from this:

    wsgi-file = /home/shelluser/apps/myapp/myproject/myproject/wsgi.py
    

    ... to this ...

    mount = /foo=/home/shelluser/apps/myapp/myproject/myproject/wsgi.py
    

    Be sure that the /foo in the mount line matches the URI path that you've assigned to the site in the dashboard.

  5. Add the following line to the end of the uwsgi.ini file:

    manage-script-name = True
    
  6. Save the file and exit your editor.

  7. Restart the application:

    /home/shelluser/apps/myapp/stop
    /home/shelluser/apps/myapp/start
    

After you've restarted the application it should then be available on /foo or whatever URI path you assigned to it.

Finally, please note that with these instructions it is not necessary to use FORCE_SCRIPT_NAME in your Django project settings.