מחרוזות שאילתה
חלק מהיחידה יסודות Django במסלול ה-Django של Coddy. שיעור 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, יש לקרוא אתsizeמתוךrequest.GET, כדי שחוסר בגודל לא יגרום לקריסה. - עבור
?size=large, יש להחזירYou ordered a large coffee.יש להציב את הגודל במשפט, כדי שגםsmallוגםmediumיעבדו. - כל גודל אחר, או היעדר גודל, יזמין קפה בגודל בינוני.
פתחו את /order/?size=huge: תראו You ordered a medium coffee.
נסו בעצמכם
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 אונליין