generated from DevPsyLab/QuartoWebsite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdjango.qmd
300 lines (191 loc) · 9.51 KB
/
django.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
---
title: "Django"
execute:
echo: true
error: true
jupyter: python3
format:
html:
code-fold: false
code-tools:
source: true
toggle: true
---
# Overview of `Django`
`Django` is a web framework used in `Python`.
## Architecture
`Django` uses a Model-View-Controller architecture.
### URL Patterns {#urlPatterns}
The URL patterns determine which [view](#views) to pass the request to for handling.
URL patterns are defined in `urls.py`.
### Views {#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](#models) and [templates](#templates).
Views are defined in `views.py`.
### Models {#models}
To perform queries against the database, each [view](#views) 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`.
#### Defining Fields {#fields}
Fields are columns/variables in the database table that are defined by [models](#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 |
| Email | 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 a `CharField`
- `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`
- `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)
- `choices`: limits the values that can be stored in that field to a set of choices that are provided
#### Migrations {#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 makemigrations`
- `showmigrations`: e.g., `python3 manage.py showmigrations`
- `migrate`: 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.
### Templates {#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.
# `Django` Documentation
<https://docs.djangoproject.com>
# Install `Django`
In terminal:
```{python}
#| eval: false
python3 -m pip install Django==5.0.4 # install Django on Mac
py -m pip install Django==5.0.4 # install Django on Windows
```
Verify installation:
```{python}
#| eval: false
python3 -m django --version # gets Django version
```
# 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:
```{python}
#| eval: false
django-admin startproject nameOfProject
```
This will create a "nameOfProject" directory in your current directory.
# Project File Structure
## `manage.py`
- runs commands
## `nameOfProject/__init__.py`
- tells `Python` that the folder contains `Python` code
## `nameOfProject/wsgi.py` and `nameOfProject/asgi.py`
- provide hooks for web servers when `Django` is running on a live website
## `nameOfProject/settings.py`
- configures the `Django` project
## `nameOfProject/urls.py`
- routes web requests based on the URL
# 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:
```{python}
#| eval: false
python3 manage.py startapp nameOfApp
```
This will create the "nameOfApp" folder and files for the app.
Then, add app to the `Installed_Apps` section of `settings.py`:
`nameOfApp`
# App File Structure
## `apps.py`
- controls settings that are specific to the app
## `models.py`
- provides the data layer, which is used to create the database schema and queries
## `admin.py`
- defines an administrative interface for the app that will allow us to see and edit the data
## `urls.py`
- URL routing specific to this app
## `views.py`
- defines the logic and control flow for handling requests
- defines the `HTTP` requests that are returned
## `tests.py`
- unit tests for testing app functionality
## `migrations/`
- holds files for migrating the database as we create and change the database schema over time
# Remove Migrations
```{python}
#| eval: false
python3 manage.py migrate zero # can insert appname before 'zero'
```
# Update Migrations
```{python}
#| eval: false
python3 manage.py makemigrations # can insert appname after 'makemigrations'
python3 manage.py migrate
```
# Run `Django` Commands
```{python}
#| eval: false
python3 manage.py NAME_OF_COMMAND
```
# Run `Django` Project
```{python}
#| eval: false
python3 manage.py runserver
```
# View in Browser
<http://localhost:8000>
<http://127.0.0.1:8000>
# `Django` Admin Console
<http://localhost:8000/admin>
<http://127.0.0.1:8000/admin>
# Query Database with ORM
Object-Relational Mapper (ORM)
```{python}
#| eval: false
python3 manage.py shell
```
# Database
<http://localhost>
```{python}
#| eval: false
python3 manage.py createsuperuser
```
# Troubleshooting
- `Django` module not found
- Make sure `Django` is installed; if so, change `python3` to `python` in the commands (or vice versa)