모든 음료를 위한 페이지
Coddy Django 여정의 Django 기초 섹션에 포함된 레슨. 23개 중 7번째.
카페의 음료는 이제 DRINKS에 저장되어 있으며, 이는 menu/views.py에 있는 딕셔너리입니다. flat-white와 같은 키는 슬러그입니다. 소문자 단어를 하이픈으로 연결한 것으로, URL에 들어가도록 만들어졌습니다.
slug 변환기는 문자, 숫자, 하이픈, 밑줄과 일치합니다. 여기서는 딕셔너리에서 조회하여 모든 직원을 위한 페이지를 제공합니다.
path("team/<slug:handle>/", views.team_member),
def team_member(request, handle):
person = STAFF[handle]
return HttpResponse(f"<h2>{person['role']}</h2>")/team/maya-cohen/의 경우 뷰는 handle="maya-cohen"을 받고 이를 키로 사용합니다. 하나의 경로와 하나의 뷰가 딕셔너리 전체를 처리하므로, 새 항목을 추가하면 새 코드 없이도 해당 페이지가 생깁니다.
챌린지
쉬움DRINKS의 모든 음료에 /drinks/ 뒤에 해당 키를 붙인 페이지를 제공하세요:
/drinks/latte/,/drinks/flat-white/및 다른 모든 키와 일치하는 하나의 경로;- 음료 이름을
<h1>에 표시한 다음 설명을<p>에 표시하는 뷰drink.
실행을 누르세요. 미리보기에 /drinks/latte/가 열립니다.
직접 해보기
from django.http import HttpResponse
DRINKS = {
"espresso": {"name": "Espresso", "price": 2.5, "description": "A short, strong shot of coffee."},
"latte": {"name": "Latte", "price": 3.5, "description": "Espresso with lots of steamed milk."},
"flat-white": {"name": "Flat White", "price": 3.75, "description": "Espresso with a thin layer of silky milk."},
"hot-chocolate": {"name": "Hot Chocolate", "price": 3, "description": "Dark chocolate melted into warm milk."},
}
def home(request):
return HttpResponse("<h1>Welcome to Corner Café</h1><p>Fresh coffee and cake every day.</p>")
def about(request):
return HttpResponse("Corner Café opened in 2026.")
def hours(request):
return HttpResponse("Open every day from 8:00 to 18:00.")
def contact(request):
return HttpResponse("Write to us at hello@cornercafe.example.")
def table(request, number):
return HttpResponse(f"<h1>Table {number}</h1>")
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Django 기초의 모든 레슨
직접 연습해 보세요: Django 플레이그라운드