Django¶
Project Directory Structure¶
To start a Django project, enter the command below in terminal:
To create an app, cd to the project root (
project_name/in this case) and run:
This creates the directory stucture below:
project_name/
├── project_name/ # website App: project-level configurations
│ ├── __init__.py
│ ├── settings.py # Link Apps: INSTALLED_APPS
│ ├── urls.py # Link apps' routes to main site
│ └── wsgi.py
│
├── app1/
│ ├── migrations/
│ ├── templates/
│ │ └── app1/
│ │ ├── base.html
│ │ └── index.html
│ ├── static/
│ │ └── style.css
│ ├── __init__.py
│ ├── admin.py # Customize administrator panel
│ ├── apps.py
│ ├── tests.py
│ ├── models.py # app database definition
│ ├── urls.py # app route
│ └── views.py # app functions
│
├── manage.py
└── db.sqlite3
Common Commands¶
Start new Django project
Add new app
Start server
Update database (after modifying
<app-name>/models.pyDjango shell
Create super user account
settings.py¶
Every time a new app is created, remember to attach this new app to the project. To do this, find INSTALLED_APPS in project_name/settings.py and add the app to the list:
urls.py¶
Every app has one urls.py and project_name/ has one urls.py. project_name/urls.py defines the url relations of every app to the site. <app-name>/urls.py defines the relations between individual functions in <app-name>/views.py and url paths within an app.
For example, project_name/urls.py might look like the code below, where flights, users and admin (default Django app) are apps in the project:
flights/urls.py may look like the code below:
The path functions essentially links the functions in views.py and url paths together in an app.
As an example, (after running the server locally) if you visit http://127.0.0.1:8000/flights/1/book, you will be on a page handled by the function book() defined in flights/views.py. This relationship is defined in path('<int:flight_id>/book', views.book, name='book'). The path right after the base url (http://127.0.0.1:8000/) is flights/ because it was defined in path('flights/', include('flights.urls')), in project_name/urls.py.