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 ๐