(十四) Django - template(part1)

Quiz的專案結構相當簡單,只需要建立測驗及結果的畫面,從quiz/urls.py來看:

1
2
3
4
urlpatterns = [
path('play/', views.play),
path('results/', views.answer_count),
]

測驗表單的畫面:
http://127.0.0.1:8000/quiz/
https://ithelp.ithome.com.tw/upload/images/20200915/20129725ijABswh1bO.png

第一步:views

1
2
3
4
5
# quiz/views.py
from django.shortcuts import renderfrom .models import Question
def play(request):
question = Question.objects.all()
return render(request, 'play.html', {'question':question})

藉由QuerySet取得所有題目question,再用render渲染play.html樣板。

第二步:template

先在template下新增play.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Easiest Harry Potter Quiz Ever</title>
</head>
<body>
<div id="set" style="padding-top: 50px;">
~The Easiest Harry Potter Quiz Ever~
</div><form action="" method="post">
<div style="padding-top: 60px;">
{% csrf_token %}
{% for q in question %}
<table>
<tr>
<td>{{ forloop.counter }}.{{q.question_text}}</td>
</tr>
{% for c in q.choice_set.all %}
<tr>
<td><input type="radio" name="{{ q.id }}" id="c-{{ forloop.counter }}"required>{{ c.choice_text }}</td>
</tr>
{% endfor %}
</table>
{% endfor %}
<hr width="50%" align="left">
<input type="submit" value="submit"/>
</div>
</form>
</body>
</html>
  1. loop在Django的固定寫法就是{% for %},一對大括號跟百分比,遞迴結尾要寫{% endfor %},否則會報錯。
  2. "forloop.counter"為遞迴的次數,我拿它當作題目的序號。
  3. {{q.question_text}}:在template,加上一個dot就可以得到你要的欄位。若要取得context裡的值,外面 要加個{{}},這是固定寫法。
  4. {% for c in q.choice_set.all %}:透過"_set.all"可以得到ForeighKey相關的物件,在這邊取得了題目的四個選項。
  5. 當頁面為form表單提交時,一般都需要在form標籤中加上{% csrf_token %},因為在settings.py有一個預設防範CSRF的模組(MIDDLEWARE中的'django.middleware.csrf.CsrfViewMiddleware'),所以若沒有添加{% csrf_token %},在資料送出後會看到下面這個畫面: https://ithelp.ithome.com.tw/upload/images/20200915/20129725LO1euXEpVh.png

小結:關於分數計算的部分明天繼續。