我正在使用 Django 構建一個聊天機器人,它可以采用調查的預設答案選項,并為不同的答案選項提供不同的分數。之后,聊天機器人會相應地將所有分數相加并列印出結果。
這是一個帶有預設答案選項的示例問題
<select name="survey1-q" data-conv-question="B?n có hay ngh? v? m?t ?i?u s? x?y ra trong t??ng lai theo h??ng t?i t?, th?m chí r?t tiêu c?c?">
<option value="survey1-never">Kh?ng bao gi?</option>
<option value="survey1-rarely">Hi?m khi</option>
<option value="survey1-sometimes">??i khi</option>
<option value="survey1-often">Th??ng xuyên</option>
<option value="survey1-veryoften">R?t th??ng xuyên</option>
</select>
這是我在 for 回圈中的 if 陳述句
<!--looping and getting the survey's result-->
{% for i in survey1-q%}
{% if survey1-q is "Kh?ng bao gi?"%}
{{score}}={{score 0}}
{% elif survey1-q is "Hi?m khi" %}
{{score}}={{score 1}}
{%elif survey1-q is "??i khi"%}
{{score}}={{score 2}}
{%elif survey1-q is "Th??ng xuyên"%}
{{score}}={{score 3}}
{%elif survey1-q is "R?t th??ng xuyên"%}
{{score}}={{score 4}}
{%endif%}
{% endfor %}
<p>?i?m c?a b?n là {{score}}</p>
但是,在調查的問題完成后,聊天機器人會自動加載回到開始階段并詢問第一個問題而不是列印 {{score}}
恐怕我在for回圈和if陳述句中呼叫變數是錯誤的,但經過研究,我仍然無法弄清楚。請幫我!謝謝!
uj5u.com熱心網友回復:
HTML 頁面不能在頁面重繪 之間存盤變數。Django 模板語言使用變數,但是當你的表單被驗證時它們會被重置,因此當頁面從后端重新加載時。
邏輯應該在后端。您的表單應該將結果發送到后端(您的 Django 視圖view.py),在那里可以用 Python 計算、存盤和/或檢索分數。視圖的輸出然后可以將模板與分數一起呈現為模板變數。
因此,假設您的 HTMLselect是將輸入作為名為 GET 引數發回的 HTML 表單的一部分survey_response,您的 Python 視圖view.py將如下所示:
from django.shortcuts import render
from django.http import HttpResponse
def your_view(request) -> HttpResponse:
if not score:
score: int = 0
survey_response: str = request.GET.get('survey_response')
if survey_response == "Hi?m khi":
score = 1
elif survey_response == "??i khi":
score = 2
elif survey_response == "Th??ng xuyên":
score = 3
elif survey_response == "R?t th??ng xuyên":
score = 4
return render(
request,
"your_template.html",
{
"score": score
},
)
然后在模板方面 ( your_template.html),您不需要任何回圈或任何邏輯,唯一的事情就是用<p>?i?m c?a b?n là {{score}}</p>.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/337555.html
