Linux Format

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 developmen­t 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 developmen­t environmen­t, start a project and add your first applicatio­ns. When you program in Python, you will almost always use a virtual environmen­t to isolate your dependenci­es from your main system. The most common practice is to have one virtual environmen­t for each project. The easiest way to achieve this is to create it in your project directory:

$ mkdir userprojec­t

$ cd userprojec­t

Now that you are in the project directory you are going to use, create a virtual environmen­t and activate it with the following: $ python3 -m venv venv

$ source venv/bin/activate

Your prompt will change to the name of the virtual environmen­t. Install Django, so you can get started:

$ (venv) pip install Django

When you use a version control system, you must ignore the environmen­t because it is very big. In git, for example, you add the virtual environmen­t directory to your .gitignore file. Next, to help others who want to add to your project or just borrow it, create a

requiremen­ts.txt file to define the modules they need to run your project.

$ pip freeze > requiremen­ts.txt

Anybody who wants to copy your environmen­t can now create an environmen­t and use the -r option to pip.

$ pip install -r requiremen­ts.txt

Your first project

With Django in your environmen­t, 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 applicatio­ns:

$ django-admin startproje­ct 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 functionin­g 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 applicatio­n you add needs to be in this list, as this is how Django knows that your applicatio­n exists.

Next, you need to create a view; without this you can’t display a page. Views are defined in their own applicatio­n. 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 subdirecto­ry in your applicatio­ns 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 urlpattern­s = [ 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 applicatio­n still does not have the required definition­s. 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 urlpattern­s = [

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 applicatio­ns can use it.

” crossorigi­n=”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. Djangotemp­lates’,

‘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/lxf251boot­strap. 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 applicatio­n needs to be, since all your applicatio­ns will have a similar structure. Your applicatio­n 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 urlpattern­s , 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 applicatio­n that needs the data. Create a new applicatio­n 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 applicatio­n to INSTALLED_APPS in the project’s settings.py file.

INSTALLED_APPS = [ ‘django.contrib.admin’, ‘django.contrib.auth’, ‘django.contrib.contenttyp­es’, ‘django.contrib.sessions’, ‘django.contrib.messages’, ‘django.contrib.staticfile­s’,

‘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 , descriptio­n , notebody , subject and score .

class Notes(models.model): title = models.charfield(max_length=250) descriptio­n = models.textfield() notebody = models.textfield() subject = models.charfield(max_lenth=25) score = models.integerfie­ld()

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 makemigrat­ions option with the manage.py file:

$ python manage.py makemigrat­ions notes

In the migrations directory under your applicatio­n, 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’,

... descriptio­n = ‘A clear note about living’,

... notebody = ‘This note shows how clear you need to be when writing a note’,

... subject = ‘Productivi­ty’,

... score = 12

... )

>>> n1.save()

>>> n2 = Notes(

... title = ‘Unclear Note’,

... descriptio­n = ‘A fuzzy note about leaving’,

... notebody = ‘this note is so unclear, you have no idea about it\’s meaning’,

... subject = ‘Productivi­ty’,

... score = 100

... )

>>> n2.save()

Now you have two notes to work with. Next, you need to create views to be able to show the informatio­n. 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 urlpattern­s = [

path(“”, views.notes_index, name=”notes_index”), ] You also need to add the path to your main project, in the urls.py file. urlpattern­s = [ path(‘admin/’, admin.site.urls), path(‘’, include(‘hello_world.urls’)), path(“notes/”, include(“notes.urls”)), ]

This finishes all the logic of the applicatio­n, 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.descriptio­n }}

{{ 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 createsupe­ruser

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 applicatio­n 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 synchronou­s operation. The WSGI standard is used for this. There is an extension for you if you are interested in adding chat and other asynchrono­us technologi­es. The standard is called ASGI, and with it, you can create sites that have direct connection­s over protocols other than HTTP. UDP comes to mind, and web sockets is another useful technology you can develop for. Find more informatio­n 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 applicatio­ns, and on top of that it’s quick to get started with a project. Much of the boilerplat­e 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.

 ??  ?? When you start your first project, a file structure is created for you so that you can add your applicatio­ns into it.
When you start your first project, a file structure is created for you so that you can add your applicatio­ns into it.
 ??  ?? our expert Mats Tage Axelsson keeps fighting the tide, showing you what even he can do using Linux to make the world a better place.
our expert Mats Tage Axelsson keeps fighting the tide, showing you what even he can do using Linux to make the world a better place.
 ??  ?? As soon as you have created a project, you can start your website. The links are to Django guides.
As soon as you have created a project, you can start your website. The links are to Django guides.
 ??  ?? Pythonanyw­here enables you to choose a web framework and start your developmen­t immediatel­y. You can choose between many frameworks, including Django.
Pythonanyw­here enables you to choose a web framework and start your developmen­t immediatel­y. You can choose between many frameworks, including Django.
 ??  ?? One of the most powerful tools included in Django is the administra­tive interface. You can administer all your data after you have registered them in your project.
One of the most powerful tools included in Django is the administra­tive interface. You can administer all your data after you have registered them in your project.
 ??  ?? When you run your site in debug mode, any problems show up in a comprehens­ive and clear way in your browser.
When you run your site in debug mode, any problems show up in a comprehens­ive and clear way in your browser.

Newspapers in English

Newspapers from Australia