2 回答

TA貢獻1807條經驗 獲得超9個贊
首先,我將模板表單方法從“GET”更改為“POST”,并添加 {% csrf_token %}。
其次,我將視圖更改為兩部分:
第一部分是當用戶第一次輸入 game2.html(GET 請求)時,它將向用戶呈現 game2.html。
第二部分基本上是我之前所做的,但這次我添加了一個響應用戶 POST 請求的案例,并從那里重定向到 Correct.html 或 Correct.html 或 Correct.html
游戲2.html
{% extends "morse_logs/base.html" %}
{% block content %}
<title>GAME 2</title>
<div>
<h1>GAME 2</h1>
<h2>2 + 2 = ?</h2>
<form method="POST">
{% csrf_token %}
<input type="number" id="ans2" name="ans2"/><br><br>
<input type="submit" name="Submit"/>
</form>
</div>
{% endblock content %}
views.py
@login_required()
def game2(request):
"""The Game2 page"""
if request.method == "GET":
return render(request, 'morse_logs/game2.html')
elif request.method == "POST":
if request.user and not request.user.is_anonymous:
user = request.user
user_score, created = userScore.objects.get_or_create(user=user)
ans2 = request.POST.get('ans2', '') #fetch the POST data from template
if ans2 == '':
ans2 = 0
ans2 = int(ans2)
if ans2 == 4:
# user's score declared in model increase 5points
# display correct and 5 points added to user
user_score.score += 5
user_score.save()
return redirect(reverse('morse_logs:correct'))
else:
# user's score declared in model has no point
# display incorrect and 0 point added to user
return redirect(reverse('morse_logs:incorrect'))

TA貢獻2021條經驗 獲得超8個贊
你應該改變你的
重定向('morse_logs:不正確的.html')
到
重定向('url_name')
如果您使用 django 版本 >2.0,還請刪除 app_name
- 2 回答
- 0 關注
- 192 瀏覽
添加回答
舉報