我想从Django模板的python代码中接收变量值。
我有两个按钮Yes
和No
。当我单击按钮之一时,我的python代码必须接收此django变量并检查True
或False
。但是我找不到有关如何使用这些变量的信息。这是我的html代码:
{% with word=words|random %}
<h1>{{ word }}</h1>
<h1>{{ word.word_ru }}</h1>
<form method="POST">
{% csrf_token %}
<input type="submit" value="no" name="Answer" >
<input type="submit" value="yes" name="Answer" >
{% endwith %}
这是我的python代码:
def index(request):
if request.method == "POST" and request.POST.get("Answer") == 'no':
return render(request, "training/training.html", {})
else:
return render(request, "training/training.html", {})
答案 0 :(得分:1)
您可以这样重写代码:
# template file
{% with word=words|random %}
<h1>{{ word }}</h1>
<h1>{{ word.word_ru }}</h1>
<form method="POST">
{% csrf_token %}
<input type="submit" value="no" name="answer_yes" >
<input type="submit" value="yes" name="answer_no" >
{% endwith %}
然后是views.py文件:
# views file
def index(request):
if 'answer_yes' in request.POST:
my_answer = request.POST.get('answer_yes')
return render(request, "training/training.html", {'Answer': my_answer})
elif 'answer_no' in request.POST:
my_answer = request.POST.get('answer_no')
return render(request, "training/training.html", {'Answer': my_answer})
应该可以,但是我没有测试。
编辑:
您可以这样隐藏变量:
<input type="hidden" value={{ word }} name="word" >
然后,从此命令获取变量值:
if request.POST:
my_answer = request.POST.get('word')
答案 1 :(得分:0)
如下
def test_view(request):
answer = True if request.POST.get("Answer") == "yes" else False
答案 2 :(得分:0)
通过隐藏的输入类型发送单词变量,或者通过ajax发送。 如果我理解正确,您想发送可变单词到您的视图吗?按钮值工作正常吗?
<form method="POST">
{% csrf_token %}
<input type="submit" value="no" name="Answer" >
<input type="submit" value="yes" name="Answer" >
<input type="hidden" value={{word}} name="word" >
</form>