Skip to content

Commit ace89cc

Browse files
20240421 - models, fields, database, troubleshooting
1 parent a7f4269 commit ace89cc

File tree

1 file changed

+117
-0
lines changed

1 file changed

+117
-0
lines changed

django.qmd

+117
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,104 @@ format:
1616

1717
`Django` is a web framework used in `Python`.
1818

19+
## Architecture
20+
21+
`Django` uses a Model-View-Controller architecture.
22+
23+
### URL Patterns {#urlPatterns}
24+
25+
The URL patterns determine which [view](#views) to pass the request to for handling.
26+
URL patterns are defined in `urls.py`.
27+
28+
### Views {#views}
29+
30+
Views provide the logic or control flow portion of the project.
31+
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.
32+
Each view we define can leverage [models](#models) and [templates](#templates).
33+
Views are defined in `views.py`.
34+
35+
### Models {#models}
36+
37+
To perform queries against the database, each [view](#views) can leverage `Django` models as needed.
38+
A `Django` model is a class with attributes.
39+
These model classes provide built-in methods for making queries on the associated database tables.
40+
Each model is a database table (i.e., spreadsheet).
41+
A model defines database fields (i.e., database columns/variables) as class attributes.
42+
Each database record is a row in the spreadsheet
43+
Models create the data layer of a `Django` app, by defining the schema or underlying structure of a database table.
44+
Models are defined in `models.py`.
45+
46+
#### Defining Fields {#fields}
47+
48+
Fields are columns/variables in the database table that are defined by [models](#models).
49+
Field types and field options are provided in the `Django` documentation here: https://docs.djangoproject.com/en/5.0/ref/models/fields/
50+
51+
Examples of field types include:
52+
53+
| Type | Field | Example Values | Notes |
54+
|-------------|-----------------|--------------------------------------------| ------------------------------|
55+
| Character | CharField | "This is a string" | requires max_length attribute |
56+
| Text | TextField | "This field is for large amounts of text." | Length of text is unbounded |
57+
| Email | EmailField | test@test.com | |
58+
| URL | URLField | www.example.com | |
59+
| Integer | IntegerField | 71 | |
60+
| Decimal | DecimalField | 71.03 | |
61+
| Boolean | BooleanField | True, False | |
62+
| DateTime | DateTimeField | datetime(1960, 1, 1, 8, 0, 0) | |
63+
| Foreign Key | ForeignKey | 1 | id of record in another table; relates a single database record of one model to that of a different model |
64+
| ManyToMany | ManyToManyField | NA | relates a given record to many records of another model |
65+
66+
`id` is an automatically generated field for all tables that Django manages.
67+
68+
Common field attributes:
69+
70+
- `max_length`: integer; defines maximum length of a `CharField`
71+
- `blank`: 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, specify `null`
72+
- `null`: 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)
73+
- `choices`: limits the values that can be stored in that field to a set of choices that are provided
74+
75+
#### Migrations {#migrations}
76+
77+
Migrations create the necessary scripts to change the database structure through time as we update our code to change our models.
78+
79+
A migration is needed when any of the following occur:
80+
81+
- a model is added
82+
- a field is added, removed, or changed (from an existing model)
83+
84+
When a new model is created, a migration creates the corresponding database table.
85+
Migrations are also needed when a field is added or removed from an existing model, or, when attributes of a field have changed.
86+
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.
87+
88+
The first migration created for a new `Django` app will create tables for the models that are defined.
89+
These migrations are called "initial migrations".
90+
91+
The commands for working with migrations are:
92+
93+
- `makemigrations`: e.g., `python3 manage.py makemigrations`
94+
- `showmigrations`: e.g., `python3 manage.py showmigrations`
95+
- `migrate`: e.g., `python3 manage.py migrate`
96+
97+
The `makemigrations` command generates migration files for later use.
98+
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.
99+
Those files are placed in the migration's folder of the corresponding app, and are automatically numbered, starting with one.
100+
Therefore, the initial migration will be named starting with one.
101+
102+
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).
103+
104+
The `migrate` command runs all the generated migrations that have not yet run.
105+
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.
106+
107+
When a migration has been created, but not yet run, we call this an "unapplied migration".
108+
This is a common source of errors during development, especially when collaborating with other developers.
109+
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.
110+
111+
### Templates {#templates}
112+
113+
Each view we define can also leverage templates, which help with the presentation layer of what the `HTML` response will look like.
114+
Each template is a separate file that consists of `HTML` along with some extra template syntax for variables, loops, and other control flow.
115+
Template files are saved in a folder called templates.
116+
19117
# `Django` Documentation
20118

21119
<https://docs.djangoproject.com>
@@ -148,6 +246,14 @@ python3 manage.py makemigrations # can insert appname after 'makemigrations'
148246
python3 manage.py migrate
149247
```
150248

249+
# Run `Django` Commands
250+
251+
```{python}
252+
#| eval: false
253+
254+
python3 manage.py NAME_OF_COMMAND
255+
```
256+
151257
# Run `Django` Project
152258

153259
```{python}
@@ -171,3 +277,14 @@ python3 manage.py runserver
171277
# Database
172278

173279
<http://localhost>
280+
281+
```{python}
282+
#| eval: false
283+
284+
python3 manage.py createsuperuser
285+
```
286+
287+
# Troubleshooting
288+
289+
- `Django` module not found
290+
- Make sure `Django` is installed; if so, change `python3` to `python` in the commands (or vice versa)

0 commit comments

Comments
 (0)