Creating a Django project

Overview

This article explains how to create a Django project in a virtualenv.

In the following examples, username would be your Shell user and example.com your website.

What version of Python is compatible with Django?

You must be using Python 3.4 or higher to use Django 2.

You must be using Python 3.6 or higher to use Django 3.

View the following links for a full list of compatible versions:

Initial setup

First, make sure you've installed a custom version of Python and created a virtual environment in your website's directory:

Next, install Django into your virtualenv:

Finally, enable Passenger on your domain:

Creating a Django project

To run the commands in this article, you must log into your server via SSH with your Shell user. View the following articles for more information:

The following instructions assume you've created a virtual environment titled venv using the links above.

  1. Run the following commands in order to create your Django project within this environment:

    The following example names the project projectname, but you can name it anything you like.

    [server]$ cd ~/example.com
    [server]$ source ~/example.com/venv/bin/activate
    (venv) [server]$ python3 venv/bin/django-admin startproject projectname

    When you run the startproject command, it creates a new folder in your site directory named whatever your Django 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/example.com). Add the following:
    import sys, os
    INTERP = "/home/username/example.com/venv/bin/python3"
    #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) sys.path.append(cwd + '/projectname') #You must add your project here sys.path.insert(0,cwd+'/venv/bin') sys.path.insert(0,cwd+'/venv/lib/python3.10.1/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 following in the passenger_wsgi.py file:

    • The path to your local python version in line #2. Run which python3 to confirm:
      (venv) [server]$ which python3
      /home/username/example.com/venv/bin/python3
    • Your virtualenv project name on lines 11 and 12
    • Your Django project name on lines 9 and 14
    • Your Python3 version on line 12
  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:
    • Open the projects settings.py file found at example.com/projectname/projectname/settings.py. Scroll to the bottom and 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. Make sure to change username to your Shell user.
    STATIC_ROOT = '/home/username/example.com/public/static/'
  4. In your /home/username/example.com/public/ directory, make sure to create this /static directory.
    (venv) [server]$ cd ~/example.com/public
    (venv) [server]$ mkdir 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:

  5. Run the collectstatic command to set up the static items for the admin interface:
    (venv) [server]$ cd ~/example.com/projectname/
    (venv) [server]$ python3 manage.py collectstatic
  6. Set up your database as required within the settings.py file. The section of the settings.py file originally looks like this:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    
  7. Edit to make the following additions with your actual database credentials:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'mydatabase',
            'USER': 'mydatabaseuser',
            'PASSWORD': 'mypassword',
            'HOST': 'mysql.example.com',
            '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.

  8. Also in your settings.py file, update the ALLOWED_HOSTS field with your domain name. At first, it appears like this:
    ALLOWED_HOSTS = []
    Update it to include your domain name.
    ALLOWED_HOSTS = ['example.com' , 'www.example.com']
  9. Navigate into your project directory:
    (venv) [server]$ cd ~/example.com/projectname

    If you followed the instructions to create a Django project in a virtualenv, mysqlclient is already installed. Confirm by running pip3 list.

    (venv) [server]$ pip3 list

    mysqlclient should display. If not run the following to install.

    (venv) [server]$ pip3 install mysqlclient
  10. Run the migrate command in your project directory:

    When running the following command, you will see this warning message:

    ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
            HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, 
    such as data truncation upon insertion, by escalating warnings into errors.
    It is strongly recommended you activate it.
    See: https://docs.djangoproject.com/en/2.2/ref/databases/#mysql-sql-mode

    This warning means your database does not have Strict Mode enabled. You can continue to install Django normally if you like, but if you would prefer your database to use Strict Mode, the only option would be to purchase a private MySQL server.

    Once added, contact DreamHost support. They will be able to adjust this setting on the server for you.

    (venv) [server]$ python3 manage.py migrate
    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, sessions
    Running migrations:
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying admin.0002_logentry_remove_auto_add... OK
      Applying admin.0003_logentry_add_action_flag_choices... 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 auth.0008_alter_user_username_max_length... OK
      Applying auth.0009_alter_user_last_name_max_length... OK
      Applying auth.0010_alter_group_name_max_length... OK
      Applying auth.0011_update_proxy_permissions... OK
      Applying auth.0012_alter_user_first_name_max_length... OK
      Applying sessions.0001_initial... OK
    
  11. Create a superuser:
    (venv) [server]$ python3 manage.py createsuperuser
    Username (leave blank to use 'username'): my_django_user
    Email address: email@example.com
    Password:
    Password (again):
    Superuser created successfully.
  12. Navigate to your /home/username/example.com directory.
    (venv) [server]$ cd /home/username/example.com
  13. Add a /tmp/restart.txt file:
    (venv) [server]$ mkdir tmp
    (venv) [server]$ touch tmp/restart.txt

    Whenever you make a change to your configuration, make sure to run the following in your site's directory to notify Passenger of the change:

    (venv) [server]$ touch tmp/restart.txt

Confirming the installation was successful

Visit your website.

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

Troubleshooting

If you notice any errors after installing, check to see if you have an .htaccess file in your site's directories. It's possible the code in it could cause issues with your installation.

ModuleNotFoundError: No module named 'django'

If you see this error when visiting your site, check your passenger_wsgi.py file. Confirm the following line points to your custom version of Python. For example, it should be 3.6 or 3.7 if you installed one of those versions.

sys.path.insert(0,cwd+'/venv/lib/python3.7/site-packages')

See also

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?