๐Ÿ“š Django - Fundamental

๐Ÿ“š Django - Fundamental
Photo by Faisal / Unsplash

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

  • setup urls.py in the app
# 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'})

Debug Tools

  • VSCode: Create a launch.json file -> select django
  • Django Debug Toolbar: follow the instructions ๐Ÿ’Ž