【发布时间】:2020-07-28 05:34:18
【问题描述】:
我正在编写一个从 game2.html 中检索答案的视图,检查答案;如果答案正确,视图会将用户重定向到正确的.html,如果答案不正确,则用户将被重定向到不正确的.html。
现在的问题是点击提交按钮后,用户不会被重定向。但是分数是更新的。
点击提交按钮后,网址将从http://localhost:8000/game2/ 更改为http://localhost:8000/game2/?ans2=4&game2Answer=Submit,而不是重定向到correct.html 或correct.html
我猜可能是我的提交按钮没有触发重定向功能的问题,或者是我在视图中编写重定向功能的方式的问题,因为如果答案正确,分数实际上会更新。
那么,在进入 if-else 语句后,我该如何修复它以使其能够重定向到正确的.html 或错误的.html。
morse_logs/views.py
@login_required()
def game2(request):
"""The Game2 page"""
if request.user and not request.user.is_anonymous:
user = request.user
def verifyGame2(val1):
user_score, created = userScore.objects.get_or_create(user=user)
if val1 == 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('morse_logs:incorrect')
else:
# user's score declared in model has no point
# display incorrect and 0 point added to user
return redirect('morse_logs:incorrect')
ans2 = request.GET.get('ans2', '')
if ans2 == '':
ans2 = 0
verifyGame2(int(ans2))
return render(request, 'morse_logs/game2.html')
game2.html
{% extends "morse_logs/base.html" %}
{% block content %}
<title>GAME 2</title>
<div>
<h1>GAME 2</h1>
<h2>2 + 2 = ?</h2>
<form action="" method="post" >
<input type="number" id="ans1" name="ans1"/><br><br>
<input type="submit" name="game1Answer"/>
</form>
</div>
{% endblock content %}
morse_logs/correct.html
{% extends "morse_logs/base.html" %}
{% block content %}
<title>Correct!</title>
<div>
<h1>Congratulations! Your answer is CORRECT!</h1>
</div>
{% endblock content %}
morse_logs/incorrect.html
{% extends "morse_logs/base.html" %}
{% block content %}
<title>Inorrect...</title>
<div>
<h1>Unfortunately! Your answer is Incorrect!</h1>
</div>
{% endblock content %}
morse_logs/urls.py
from django.urls import path, include
from morse_logs import views
app_name = 'morse_logs'
urlpatterns = [
#The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name.
# Home Page
path(r'', views.index, name='index'),
# Page that shows all topics
path(r'topics/', views.topics, name='topics'),
path(r'cipher/', views.cipher, name='cipher'),
path(r'decipher/', views.decipher, name='decipher'),
path(r'tutorialIndex/', views.tutorialIndex, name='tutorialIndex'),
path(r'gameDirectory/', views.gameDirectory, name='gameDirectory'),
path(r'game1/', views.game1, name='game1'),
path(r'game2/', views.game2, name='game2'),
path(r'correct/', views.correct, name='correct'),
path(r'incorrect/', views.incorrect, name='incorrect'),
]
【问题讨论】:
-
将
redirect('morse_logs:incorrect.html')替换为redirect('incorrect')。redirect('morse_logs:correct.html')的类似变化。 -
现在显示页面未找到 404
-
您是否为
incorrect和correct视图配置了网址?将您的 urls.py 添加到问题中。 -
是的,我有它
-
对于哪个 URL,Django 返回 404?您是否可以直接访问该网址(例如从浏览器)?
标签: html django django-forms django-views django-templates