详细信息:
<form id="answer_form" class="form-horizontal" action="{% url 'puzzle:update' puzzle.id %}" method="POST" onSubmit="return ValidateAnswer();">
{% csrf_token %}
<p>Please entry your answer below: (Case insensitive)</p>
<div class="form-group col-xs-12">
<input id="player_answer" maxlength="30" name="player_answer" type="text">
</div>
<div class="form-group col-xs-12">
<button id="submit_answer_btn" class="btn btn-success" type="submit">Submit</button>
</div>
</form>
<script>
function ValidateAnswer() {
var player_answer = document.getElementById("player_answer");
if(player_answer.value == {{ puzzle.answer }}) {
alert("Congratulations!");
} else {
alert("Wrong answer!");
return false;
}
}
</script>
在url.py中
app_name = 'puzzle'
urlpatterns = [
url(r'^(?P<pk>[0-9]+)/$', login_required(views.PuzzleDetailView.as_view()), name='detail'),
url(r'^(?P<puzzle_id>[0-9]+)/update/$', views.update_user_game_history, name='update'),
]
在views.py
中class PuzzleDetailView(DetailView):
model = Puzzle
template_name = 'puzzle/detail.html'
def update_user_game_history(request, puzzle_id):
player_game_history = PlayerGameHistory.objects.get(user=request.user)
solved_puzzle = Puzzle.objects.get(id=puzzle_id)
player_game_history.score += solved_puzzle.point
player_game_history.save()
return HttpResponseRedirect('/')
我要做的是点击提交按钮,通过第二个网址,转到views.py中的 update_user_game_history 功能。
但是,每次我提交时,流程都会尝试通过1st url转到PuzzleDetailView。我在终端
中得到方法不允许(POST):/ 2 /答案 0 :(得分:1)
我不确定这是否解决了您的问题,但基本上在视图中您没有办法确保该方法是否为“POST”。要解决此问题,您可以在代码中添加以下行:
def update_user_game_history(request, puzzle_id):
if request.method == 'POST':
player_game_history = PlayerGameHistory.objects.get(user=request.user)
solved_puzzle = Puzzle.objects.get(id=puzzle_id)
player_game_history.score += solved_puzzle.point
player_game_history.save()
return HttpResponseRedirect('/')
但根据您的示例,没有必要调用表单,因为您没有使用它。我的建议是改进这个视图,因为只有一个网址,你可以多次得分
答案 1 :(得分:0)
非常感谢Alasdair。检查渲染的表单标签后,我发现了问题。表单标记中的action属性值是错误的。它仍然是#34;#&#34;。 Chrome后退按钮似乎无法从服务器检索最新页面。它只会重新加载之前收到的内容。