2. New Django

Robert Crowther Feb 2022
Last Modified: Feb 2023

PrevNext

Virtual evironment

I’d do this in userspace. If I’m not deploying, and I’m not, let’s avoid permissions.

Make a folder somewhere,

mkdir Server

In that, make a virtualenv,

cd Server
python3 -m venv siteNameEnv

Activate the virtual environment on at least two terminal tabs (one is needed for server running),

cd siteNameEnv
source bin/activate

Create a Django

Install Django (should have Pip),

pip install Django

Create a project skeleton,

django-admin startproject siteName

Run server,

cd siteName
./manage.py runserver

Ignore migration errors. Check server,

http://127.0.0.1:8000/

Use a different port

Why use a different port? Especially in development? Because you run more than one Django but do not want to stop and start servers.

The default is port 8000. Several ways to use a different port. For development, easiest way is to state the port to runserver,

./manage.py runserver 7900

However, easiest is not best. When you forget what ports Django instances are running on, you can end in a tangle. Better to have a policy for port allocation, then code in. Unfortunately, Django has no setting to change server port (that would be the natural, fully maintainable way). Best I can find on the web is this suggestion—alter manage.py with the two lines commented in the code below,

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'siteName.settings')
    try:
        from django.core.management import execute_from_command_line

        # Add this line...
        from django.core.management.commands.runserver import Command as runserver
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

    # Add this line...
    runserver.default_port = "8080"
    execute_from_command_line(sys.argv)

This will not interfere with manage.py, but will change the port.

I add there is more you could do. You could bypass manage.py with a BASH script. You could create and load a setting. But, until Django provides a builtin solution, I prefer a minimum‐code hack.

Settings

Add this to settings.py,

BASE_DIR = Path(__file__).resolve().parent.parent

# Add this
PROJECT_DIR = Path(__file__).resolve().parent

And, if you want/need, change the localisation information,

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'

Database

At this point you can plug in another database. I would not. At this point Django is using SQLite, and that’s ok. If you want to use a different database, later I will tell you how to drop.

Pros and Cons of installing a different database (at this point)

The case against is strong. Setting up another kind of database is a large step. It will turn you from forward progress. It will involve you in much separate, targetted‐at‐the‐database activity. Whereas the builtin Django SQLite database has encapsulated deployment and pre‐configured tools. And, for most new sites, you do not know the shape of the data—you have not built or tested models. For a new site, you will be uploading test data, not data you intend for final display. Think about this—Django includes a builtin SQLite database to avoid this step. The SQLite builtin is effective—other web frameworks have copied the idea.

What is the case for installing another database? As far as I can guess, only one. You have an established development path, where you know which database will be used and, importantly, how it will be deployed. You want to move to your usual tools immediately. And, likely, you want to upload pre‐existing data. That may be significant, especially if you are, for example, upgrading an existing site.

On this subject, there’s web‐comment I’ll argue. Nearly every tutorial I have ever read about web‐frameworks (not only Django) introduces the installation and configuration of the database with the opinion that this is a ‘necessary’ and ‘professional’ activity. First, in Django, the SQLite database means it is not ‘necessary’ to install a database. And second, there is nothing ‘unprofessional’ about SQLite. It’s coded by MySQL, one of the major database providers. It’s used in Firefox and other huge applications. It has a near‐full and highly compatible SQL implementation. The only objections are that SQLite is slower than a database with more complex save and query, and that SQLite is short of a few advanced API methods. These are weak arguments.

In short: it is possible to present a case that you should be using another database, for example, you have a 120,000‐record dump, ready formatted. But if you have that, you do not need this guide. Otherwise, you should be using the SQLite database. It is ‘easier’, which in this case means removing an unnecessary development step. And it is encapsulated within Django, which is better coding, API, backup, and maintenance. Which is why I will not talk about changing the database.

Backup

Now get the /siteName folder, which contains the website data, backed up. I’ve deleted this before… by accident… Some people backup only the database. Problem with this is you have a lot of valuable other data like code for models, config, static files, and locally‐stored media. Over to you, yes, your backup depends on the purpose and style of your site. But I’m saying, as basic, backup that folder, which will include everything.

Hiding the SECRET_KEY

There is a problem with file backup. Store a site in a public place like Github, and you will probably start getting warnings. The site contains a SECRET_KEY in settings,py and, rightly, Github and maybe others will warn about this. From what I see, a lot of people ignore the warnings. Here’s another solution—cut and paste the key into a separate file called e.g. secret_key.py, then import it into settings.py,

from .secret_key import SECRET_KEY

Now you can for example, ‘.gitignore’ ’secret_key.py’.

Anyway, backup now. Get the insurance in place.

Initialise the database

Note that a Django skeleton provides a stock set of apps for typical use. For some uses, you may want to remove or add applications, which is done in settings.py. But mostly this can be done later, so ignored at this point.

Run all initial migrations,

./manage.py migrate

Superuser

Create, and note details for, a superuser. That needs a user, email, and password,

./manage.py createsuperuser

If necessary, run the server, then goto this URL,

http://127.0.0.1:8000/admin/

Put in the details you entered, save logon details to your browser.

DB Shell

To use the DBshell, you need an sqlite terminal client on your system. The dbshell command,

./manage.py dbshell

has no special code, it runs the sqlite terminal client. On Debian,

apt-get install sqlite3

Right, you are up and running.