Introduction to Django
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:
| Database | Typical use |
|---|---|
| a popular choice in production | |
| widely available on web hosts | |
| the default for new projects: one file, no server | |
| large 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 pageModels, views, templates (MVT)
| Part | Job | File |
|---|---|---|
| Model | the data and the rules for it; one class per database table | models.py |
| View | handles a request and returns a response | views.py |
| Template | the HTML, with placeholders for data | templates/*.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.titleA 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.