Create Project#
poetry init
portry add django
django-admin startproject my_site . # period to current directory
python manage.py runserver [9000] # port is optional
- Every Django project consists of multiple
apps
.
Create APP#
python manage.py startapp playground
├── manage.py
├── playground
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py # config setting
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py # request handlers
Register APP#
- you can use both methods.
# settings.py
INSTALLED_APPS = [
# ...
'playground',
# ...
]
# settings.py
INSTALLED_APPS = [
# ...
'playground.apps.PlaygroundConfig',
# ...
]
Views#
# playground/views.py
from django.shortcuts import render
from django.http import HttpResponse
def say_hello(request):
return HttpResponse('Hello World')
Maps URLs to Views#
# playground/urls.py
import django.urls import path
from . import views
# URLConf: need to be this variable name 💡
urlpatterns = [
path('playground/hello', views.say_hello)
]
- include the app’s url in the project level
# storefront/urls.py
from django.contrib import admin
from django.urls import path, include # add include
urlpatterns = [
path('admin/', admin.site.urls),
path('playground/', include('playground.urls')) # add this
]
Use Templates#
- create templates folder under playground and create a new file hello.html.
<!-- playground/templates/hello.html -->
{% if name %}
<h1>Hello {{ name }}</h1>
{% else %}
<h1>Hello World</h1>
{% endif %}
- refine the views.py (request handler)
# playground/views.py
from django.shortcuts import render
#from django.http import HttpResponse
def say_hello(request):
return render(request, 'hello.html', {'name': 'Jamie'})
- VSCode: Create a
launch.json
file -> select django
- Django Debug Toolbar: follow the instructions 💎