python3 -m pip install Django==5.0.4 # install Django on Mac
py -m pip install Django==5.0.4 # install Django on WindowsDjango
1 Overview of Django
Django is a web framework used in Python.
1.1 Architecture
Django uses a Model-View-Controller architecture.
1.1.1 URL Patterns
The URL patterns determine which view to pass the request to for handling. URL patterns are defined in urls.py.
1.1.2 Views
Views provide the logic or control flow portion of the project. A view is a Python callable, such as a function that takes an HTTP request as an argument and returns an HTTP response for the web server to return. Each view we define can leverage models and templates. Views are defined in views.py.
1.1.3 Models
To perform queries against the database, each view can leverage Django models as needed. A Django model is a class with attributes. These model classes provide built-in methods for making queries on the associated database tables. Each model is a database table (i.e., spreadsheet). A model defines database fields (i.e., database columns/variables) as class attributes. Each database record is a row in the spreadsheet Models create the data layer of a Django app, by defining the schema or underlying structure of a database table. Models are defined in models.py.
1.1.3.1 Defining Fields
Fields are columns/variables in the database table that are defined by models. Field types and field options are provided in the Django documentation here: https://docs.djangoproject.com/en/5.0/ref/models/fields/
Examples of field types include:
| Type | Field | Example Values | Notes |
|---|---|---|---|
| Character | CharField | “This is a string” | requires max_length attribute |
| Text | TextField | “This field is for large amounts of text.” | Length of text is unbounded |
| EmailField | test@test.com | ||
| URL | URLField | www.example.com | |
| Integer | IntegerField | 71 | |
| Decimal | DecimalField | 71.03 | |
| Boolean | BooleanField | True, False | |
| DateTime | DateTimeField | datetime(1960, 1, 1, 8, 0, 0) | |
| Foreign Key | ForeignKey | 1 | id of record in another table; relates a single database record of one model to that of a different model |
| ManyToMany | ManyToManyField | NA | relates a given record to many records of another model |
id is an automatically generated field for all tables that Django manages.
Common field attributes:
max_length: integer; defines maximum length of aCharFieldblank: True or False; determines whether a field is (not) required; with an integer field, the submission of a blank field is recorded as zero, which is indistinguishable from a value of zero; if you want to specify the value as unknown, specifynullnull: True or False; determines whether a field can be stored as a null (i.e., there is no data for that field in a given record)choices: limits the values that can be stored in that field to a set of choices that are provided
1.1.3.2 Migrations
Migrations create the necessary scripts to change the database structure through time as we update our code to change our models.
A migration is needed when any of the following occur:
- a model is added
- a field is added, removed, or changed (from an existing model)
When a new model is created, a migration creates the corresponding database table. Migrations are also needed when a field is added or removed from an existing model, or, when attributes of a field have changed. All of these changes to a model’s file need a corresponding change to the database, and for these purposes migrations need to be created, and then run.
The first migration created for a new Django app will create tables for the models that are defined. These migrations are called “initial migrations”.
The commands for working with migrations are:
makemigrations: e.g.,python3 manage.py makemigrationsshowmigrations: e.g.,python3 manage.py showmigrationsmigrate: e.g.,python3 manage.py migrate
The makemigrations command generates migration files for later use. It reads the current model’s file and inspects the current state of the database to determine what changes need to be made to make the database structure match the model’s file. Those files are placed in the migration’s folder of the corresponding app, and are automatically numbered, starting with one. Therefore, the initial migration will be named starting with one.
The showmigrations command shows which migrations exist for the app, and which have not yet been run (empty brackets indicate the migration has not been run; an “X” in brackets indicates that the migration has been run).
The migrate command runs all the generated migrations that have not yet run. We can also run migrations for a specific app to a specific number of migration, by using the migrate command with an app name and a number.
When a migration has been created, but not yet run, we call this an “unapplied migration”. This is a common source of errors during development, especially when collaborating with other developers. With this in mind, be sure that when working on a team, to coordinate carefully who is changing which model, and to look for new migration files when pulling in code changes.
1.1.4 Templates
Each view we define can also leverage templates, which help with the presentation layer of what the HTML response will look like. Each template is a separate file that consists of HTML along with some extra template syntax for variables, loops, and other control flow. Template files are saved in a folder called templates.
2 Django Documentation
3 Install Django
In terminal:
Verify installation:
python3 -m django --version # gets Django version4 Create a Django Project
From the command line, cd into a directory where you’d like to store your code, then run the following command:
django-admin startproject nameOfProjectThis will create a “nameOfProject” directory in your current directory.
5 Project File Structure
5.1 manage.py
- runs commands
5.2 nameOfProject/__init__.py
- tells
Pythonthat the folder containsPythoncode
5.3 nameOfProject/wsgi.py and nameOfProject/asgi.py
- provide hooks for web servers when
Djangois running on a live website
5.4 nameOfProject/settings.py
- configures the
Djangoproject
5.5 nameOfProject/urls.py
- routes web requests based on the URL
6 Create a Django App
A Django app is a component in a Django project. It has a folder with a set of Python files. Each Django app has a specific purpose. Each Django project may have one or many Django apps.
Examples of Django apps include:
- blog
- forum
- wiki
To create a Django app, cd into the project folder type the following:
python3 manage.py startapp nameOfAppThis will create the “nameOfApp” folder and files for the app.
Then, add app to the Installed_Apps section of settings.py:
nameOfApp
7 App File Structure
7.1 apps.py
- controls settings that are specific to the app
7.2 models.py
- provides the data layer, which is used to create the database schema and queries
7.3 admin.py
- defines an administrative interface for the app that will allow us to see and edit the data
7.4 urls.py
- URL routing specific to this app
7.5 views.py
- defines the logic and control flow for handling requests
- defines the
HTTPrequests that are returned
7.6 tests.py
- unit tests for testing app functionality
7.7 migrations/
- holds files for migrating the database as we create and change the database schema over time
8 Remove Migrations
python3 manage.py migrate zero # can insert appname before 'zero'9 Update Migrations
python3 manage.py makemigrations # can insert appname after 'makemigrations'
python3 manage.py migrate10 Run Django Commands
python3 manage.py NAME_OF_COMMAND11 Run Django Project
python3 manage.py runserver12 View in Browser
13 Django Admin Console
14 Query Database with ORM
Object-Relational Mapper (ORM)
python3 manage.py shell15 Database
python3 manage.py createsuperuser16 Troubleshooting
Djangomodule not found- Make sure
Djangois installed; if so, changepython3topythonin the commands (or vice versa)
- Make sure