クエリ文字列
CoddyのDjangoジャーニー「Djangoの基礎」セクションの一部。レッスン 8/23。
注文ページには常に「中」と表示されます。顧客が選んだサイズは、疑問符の後に住所として渡せます: /order/?size=large。
この部分はクエリー文字列です: name=valueのペアを&でつなぎます。これはルートの一部ではないため、path("search/", ...)は/search/?q=cakeにも一致します。ビューはrequest.GETからペアを読み取ります。これは辞書のように機能します:
def search(request):
word = request.GET.get("q", "")
if len(word) > 30:
word = word[:30]
return HttpResponse(f"Results for {word}").get()は名前が存在しない場合のデフォルト値を受け取ります。一方、request.GET["q"]ではエラーになります。すべての値はテキストとして渡され、誰でも?の後に何でも入力できるため、値を使う前に確認しましょう。一部の値だけを受け付けるには、その値を許可された値のリストと比較し、それ以外の場合はデフォルト値を使います。
チャレンジ
簡単注文ページでアドレスからサイズを読み取るようにします。
orderビューで、サイズが指定されていない場合にエラーにならないよう、request.GETからsizeを読み取ります。?size=largeの場合は、You ordered a large coffee.と応答します。文にサイズを含めることで、smallとmediumも使えるようにします。- それ以外のサイズ、またはサイズが指定されていない場合は、mediumを注文します。
/order/?size=hugeを開くと、「mediumのコーヒーをご注文いただきました。」と表示されます。
自分で試してみよう
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>")
def drink(request, slug):
item = DRINKS[slug]
return HttpResponse(f"<h1>{item['name']}</h1><p>{item['description']}</p>")
def order(request):
size = "medium"
return HttpResponse(f"You ordered a {size} coffee.")
Djangoの基礎のすべてのレッスン
自分で練習してみよう: Djangoプレイグラウンド