Database-driven websites
Mats Tage Axelsson takes you on a tour of the Django framework, and explains the ways you can learn more about it.
Mats Tage Axelsson takes you on a tour of the Django framework.
The Django web framework was named after the famous guitarist Django Reinhardt and was first created by web developers at a small newspaper in Kansas. The main goals of Django is to enable fast development of complex websites with database needs. It is very easy to get started if you have some Python experience; the package includes a simple web server and an optional admin interface.
In the stable version (Django 2.2), you need to have at least Python 3.4 – it works well with Python 3.7.3. Do your best to stay at the highest stable version when you start a new project. Django always aims to follow the standards set in PEP3333, usually known as WSGI.
Twang the Django
The most obvious way to use Django is to create a CMS and create your own blog. With the vast array of packages available, you can create many other sites. It already powers many of the big websites on the internet and has many packages, which support the creation of web stores, social networks and even scientific computing sites.
The first thing you notice is that Django helps you get started in a serious way. When you start a project, you use management commands and they create most of the files that you need to build a website. When you need a function, the first thing to do is to look for a package that already exists. Inserting most packages into your project involves a simple install command and editing the main settings file.
In this tutorial, you will see how to set up your development environment, start a project and add your first applications. When you program in Python, you will almost always use a virtual environment to isolate your dependencies from your main system. The most common practice is to have one virtual environment for each project. The easiest way to achieve this is to create it in your project directory:
$ mkdir userproject
$ cd userproject
Now that you are in the project directory you are going to use, create a virtual environment and activate it with the following: $ python3 -m venv venv
$ source venv/bin/activate
Your prompt will change to the name of the virtual environment. Install Django, so you can get started:
$ (venv) pip install Django
When you use a version control system, you must ignore the environment because it is very big. In git, for example, you add the virtual environment directory to your .gitignore file. Next, to help others who want to add to your project or just borrow it, create a
requirements.txt file to define the modules they need to run your project.
$ pip freeze > requirements.txt
Anybody who wants to copy your environment can now create an environment and use the -r option to pip.
$ pip install -r requirements.txt
Your first project
With Django in your environment, you can now use it to create a new project. This is where Django shines – it creates many files for you to fill in with your software. You use the django-admin command to create projects and applications:
$ django-admin startproject personal-portfolio
The above command uses the standard Django template. You can use other templates as you get more advanced, but for now this is plenty. The script creates most of what you need to have a functioning web app. If you’re following along, start the web server; it’s
When you open this file it contains these django.* entries – all you need to add is the hello_world entry. Each application you add needs to be in this list, as this is how Django knows that your application exists.
Next, you need to create a view; without this you can’t display a page. Views are defined in their own application. Look in the just created hello_world directory; there will be a views.py file, which already contains import code.
from django.shortcuts import render def hello_world(request): return render(request, ‘hello_world.html’, {})
You now have a link to the file hello_world.html, which we will need to create next. The render function looks for this template in the templates subdirectory in your applications directory. Create the directory and the file and put the standard ‘Heading 1’ code into it:
hello, World!
For the project to reach your files, you need to register it in the urls.py file.
from django.contrib import admin from django.urls import path, include urlpatterns = [ path(‘admin/’, admin.site.urls), path(‘’, include(‘hello_world.urls’)),
Note that you are adding the second path statement and the include module on the second line. You now have the URL defined in your main project, but the application still does not have the required definitions. To add those you need to add the urls.py file inside the hello_world directory. from django.urls import path from hello_world import views urlpatterns = [
path(‘’, views.hello_world, name=’hello_world’),
With all this you can restart your web service and see your webpage. The text is just bold and big, and there are no other styling to it, so your next step is to add CSS. The most popular CSS framework is Bootstrap. To add it, just put it in your base.html file for your project so that all applications can use it.
” crossorigin=”anonymous”>
{% block page_content %}{% endblock%}
You also need to add the template to your settings. py file in your main project directory. The DIRS entry needs to be updated.
TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django. Djangotemplates’,
‘DIRS’: [“personal_portfolio/templates/”], ‘APP_DIRS’: True,
‘OPTIONS’: { ‘context_processors’: [ ‘django.template.context_processors.debug’, ‘django.template.context_processors.request’, ‘django.contrib.auth.context_processors.auth’, ‘django.contrib.messages.context_processors. messages’, ], },
}, ]
You can read more details about how to style a page at http://bit.ly/lxf251bootstrap. When you check your webpage now, the style is slightly different. With more Bootstrap magic you can add banners and other cool stuff.
A good exercise is to now recap where your application needs to be, since all your applications will have a similar structure. Your application has its own directory structure and needs to be added in the project’s settings.py under the INSTALLED_APPS section. There is one entry in the urls.py file under urlpatterns , and that’s it for a static page.
Object Relational Mapper
When you need to have a database to handle users, you need a few more steps. In Django you use an Object Relational Mapper (ORM). To add it, you need to fill in a few values about the application that needs the data. Create a new application named notes .
$ python manage.py startapp notes
The resulting directory contains the necessary files; the most important for databases is models.py. The first thing to do is to add your new application to INSTALLED_APPS in the project’s settings.py file.
INSTALLED_APPS = [ ‘django.contrib.admin’, ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.messages’, ‘django.contrib.staticfiles’,
‘notes’, ]
The next job is to add your data structure in the models.py file. You write this as a class which is derived from Django’s own class ‘models’.
The data we need now in this example are title , description , notebody , subject and score .
class Notes(models.model): title = models.charfield(max_length=250) description = models.textfield() notebody = models.textfield() subject = models.charfield(max_lenth=25) score = models.integerfield()
This defines what one table should look like in the database. To actually create the database, you need to create a migration and later run it. The command is part of Django, so you use the makemigrations option with the manage.py file:
$ python manage.py makemigrations notes
In the migrations directory under your application, notes, there are now a new file named 0001_initial.py.
In that file you have all the code needed to create the database using the migrate option:.
$ python manage.py migrate notes
The last command creates the specific database that you want to use; you could skip the notes
parameter if you want to create all databases. That would include all standard databases that Django recommends, but this is not necessary for our example.
Since we have left everything as standard, you also have a sqlite3 database file in your project directory. You can use other databases, of course.
Django unshelled
Before you have a lot of users you will not have much data in your database. To take care of that you can start the Django shell to add data:
$ python manage.py shell
>>> n1 = Notes(
... title = ‘Clear Note’,
... description = ‘A clear note about living’,
... notebody = ‘This note shows how clear you need to be when writing a note’,
... subject = ‘Productivity’,
... score = 12
... )
>>> n1.save()
>>> n2 = Notes(
... title = ‘Unclear Note’,
... description = ‘A fuzzy note about leaving’,
... notebody = ‘this note is so unclear, you have no idea about it\’s meaning’,
... subject = ‘Productivity’,
... score = 100
... )
>>> n2.save()
Now you have two notes to work with. Next, you need to create views to be able to show the information. First you must add code to your notes directory: from django.shortcuts import render from notes.models import Notes def note_index(request): notes = Notes.objects.all() context = {
‘notes’: notes } return render(request, ‘notes_index.html’, context) This queries the entire database and returns it in the notes_index.html file – not yet created. First, you need to add the view to your notes/urls.py file:
from django.urls import path from . import views urlpatterns = [
path(“”, views.notes_index, name=”notes_index”), ] You also need to add the path to your main project, in the urls.py file. urlpatterns = [ path(‘admin/’, admin.site.urls), path(‘’, include(‘hello_world.urls’)), path(“notes/”, include(“notes.urls”)), ]
This finishes all the logic of the application, but you still need to add the HTML templates that you pointed to in the earlier code – so now let’s create the notes_ index.html template file.
{% extends “base.html” %}
{% load static %)
{% block page_content %}
notes
{% for note in notes %}
{{ notes.title }}
{{ notes.description }}
{{ notes. notebody }}
{{ notes.subject }}
{{ notes.score }}
{% endfor %}
{% endblock page_content %}>
Now you can view the data in your database. When you need to administer your site, you can create a superuser to manage it:
$ python manage.py createsuperuser
After you have created this user, log on to the admin address on your site and use the interface. With this tool, you can now create and destroy the database and perform other tasks relating to your site.
Next, you can start designing a new application that people can sign up to – packages are available for Oauth2 if you want to support this. The amount of CMSS and shopping frameworks is staggering. In fact, there are so many to choose from that you can afford to be picky and only choose the ones that suit you best. Whether you want special features, for example, or the most active project, you can find it on the Django
Packages website (see box on page 83).
In this article we have only covered regular webpages, meaning synchronous operation. The WSGI standard is used for this. There is an extension for you if you are interested in adding chat and other asynchronous technologies. The standard is called ASGI, and with it, you can create sites that have direct connections over protocols other than HTTP. UDP comes to mind, and web sockets is another useful technology you can develop for. Find more information at https://realpython.com, which has a lot of very useful tutorials.
In conclusion, the Django framework is vast and can be used for a wide range of applications, and on top of that it’s quick to get started with a project. Much of the boilerplate code is created for you once the initial setup has been completed, so you don’t have to type things you already know, or things you haven’t figured out especially for this project. Dive in and have a play around to discover Django’s power.