While Django was created in 2005 by a newspaper web team, it is now a generic web development framework used by Big sites such as Instagram, Pinterest or BitBucket. Letβs see in 5 minutes how 50 lines of code can create a fully featured CRUD modern web app.
Introduction
A Django project consists of multiple apps. Each app is structured following the MVT pattern: Models (Database entities with mappings), Views (same as the MVC βcontrollersβ) and Templates (same as the MVC βviewsβ):
βββ blog/
β βββ models.py
β βββ views.py
| βββ templates/
βββ api/ # same structure as above
βββ forum/ # same structure as above
βββ project_settings/
Installation and first project
$ python --version # 3.7.0
$ pip install django # 2.1.5
$ django-admin startproject django_overview && cd django_overview && tree
βββ manage.py # main management command: run server, create app, migrate db..
βββ django_overview/
βββ settings.py # project-wide settings (installed apps, db settings, encoding key..)
βββ urls.py # main router. Most of the time calls other apps' router
βββ wsgi.py # for deployment
$ ./manage.py runserver
Starting development server at http://127.0.0.1:8000/
Annnd check that everythingβs working as expected π:
Install admin
Django comes with a fully featured authentication, permissions and backoffice systems. You first need to update the database with the default migrations. To apply them, run the command migrate
. Then, create an admin with createsuperuser
and head to http://127.0.0.1:8000/admin:
$ ./manage.py migrate
$ ./manage.py createsuperuser
Username: admin
Password: admin
The Django admin home, with groups, users and password change:
And the Update entity form, with breadcrumbs and the history of updates:
Dead simple CRUD app
Letβs create our first CRUD app, an e-commerce store with sellable products. We got X steps:
- Create the app structure with
startapp
- Enable the app in the project
- Create our model for the database schema
- Update the database with
makemigrations
andmigrate
- Activate the admin interface
Create the app
$ chmod +x ./manage.py && ./manage.py startapp shop && tree # for Windows, just do "python manage.py startapp blog"
| manage.py
βββ shop # app folder
β β admin.py # blog backend
β β apps.py # application name
β β models.py # 1st main file: holds entities with db schema
β β tests.py # see XXX for testing with django
β β views.py # 2nd main file: holds routes & controllers
β ββββmigrations # contains .py files for automatic database migrations
ββββdjango_overview # no change here
Activate the app
And activate the shop
app in the django_overview/settings.py
whitelisted apps:
INSTALLED_APPS = [
'shop',
# ...
]
Create the db schema
Edit shop/models.py
to create our Product
model:
from django.db import models
class Product(models.Model):
created_datetime = models.DateTimeField(auto_now_add=True)
edited_datetime = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=255)
notation = models.IntegerField(default=0)
description = models.CharField(max_length=255, default='', blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.name+'('+str(self.id)+')'
Update the db
$ ./manage.py makemigrations # creates shop/migrations/0001_initial.py
$ ./manage.py migrate # runs shop/migrations/0001_initial.py
Activate the django app admin
Open shop/admin.py
and add the following:
from django.contrib import admin
from .models import Product
admin.site.register(Product)
Thatβs it! Refresh the browser for http://127.0.0.1:8000/admin/ and you can see that Django has created a new entry to do any CRUD operations:
New home with the Shop > Products
:
Add a product:
Sweet!!
Conclusion
Letβs do a quick coverage report with coverage.py
(pip install coverage
):
$ coverage run --omit manage.py --source . manage.py runserver
# Go to http://127.0.0.1:8000/admin/ to run at least 1 page, then Ctrl-C to exit program
$ coverage report
Name Stmts Miss Cover
-----------------------------------------------------
django_overview/__init__.py 0 0 100%
django_overview/settings.py 18 0 100%
django_overview/urls.py 3 3 0%
django_overview/wsgi.py 4 4 0%
shop/__init__.py 0 0 100%
shop/admin.py 3 0 100%
shop/apps.py 3 3 0%
shop/migrations/0001_initial.py 5 5 0%
shop/migrations/__init__.py 0 0 100%
shop/models.py 10 0 100%
shop/tests.py 1 1 0%
shop/views.py 1 1 0%
-----------------------------------------------------
TOTAL 48 17 65%
Thatβs the power of djangoβ¦ Less than 50 lines of code for:
- Authentication (login/logout)
- User, groups and permissions management
- CRUD management via dedicated Admin interface
- Database migration
- Database abstraction (we worked with the standard SQLite database, but see other supported DBs)
- MVC style, renamed as MVT:
- Models
- Views (shop/views.py which acts as a controller)
- Templates (shop/templates/index.html with Django templating syntax)
This tutorial is part of The Django Series:
- Django advanced Frontend tips β¬ οΈ
- Django advanced Admin tips β¬ οΈ
Reference:
- https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction
- https://www.djangoproject.com/start/overview/