CodeMIRAI
0 XP

Introduction to Django

2 min read Quiz included

Django is a Python web framework: a toolkit for building websites and web APIs. It was created in 2005 at a newspaper, and it powers Instagram, Pinterest, Mozilla, Disqus and thousands more.

Batteries included

Django ships with the pieces most websites need, ready to use:

  • an ORM to work with databases using Python instead of SQL,
  • an automatic admin site for managing your data,
  • URL routing, templates and forms,
  • user accounts and authentication,
  • strong security defaults: protection against SQL injection, cross-site scripting (XSS), cross-site request forgery (CSRF) and clickjacking.

Its ORM works with these databases out of the box:

DatabaseTypical use
PostgreSQLa popular choice in production
MySQL · MariaDBwidely available on web hosts
SQLitethe default for new projects: one file, no server
Oraclelarge organisations

How a request flows

Diagram
Browser requests /courses/
   → urls.py   matches the URL to a view
   → views.py  the view gets data (through models) and picks a template
   → models.py the ORM queries the database
   → template  fills HTML with the data
   ← the browser receives the finished HTML page
Browserurls.pywhich view?viewviews.pyModel → databaseTemplateHTML with {{ data }}HTTP response: the finished page
The URL picks a view; the view asks models for data and hands it to a template; the rendered HTML goes back to the browser.

Models, views, templates (MVT)

PartJobFile
Modelthe data and the rules for it; one class per database tablemodels.py
Viewhandles a request and returns a responseviews.py
Templatethe HTML, with placeholders for datatemplates/*.html

Many frameworks call this pattern MVC; Django's "view" plays the controller's role, and the template is the view.

A taste of Django code

A model:

Python
from django.db import models

class Course(models.Model):
    title = models.CharField(max_length=100)
    lessons = models.PositiveIntegerField(default=0)
    published = models.BooleanField(default=True)

    def __str__(self):
        return self.title

A view that lists published courses:

Python
from django.shortcuts import render
from .models import Course

def course_list(request):
    courses = Course.objects.filter(published=True).order_by("title")
    return render(request, "courses/list.html", {"courses": courses})

That's real, complete Django code. The following lessons build up to it step by step.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.