我想创建一个“index.html”Django 模板,其中包含一个按钮。按下按钮时,我想呈现模板“home.html”,它本身显示值“123”。 (当然,有一种更简单的方法来完成这个特定的任务——但我正在学习 Django,所以想尝试这种方法。)
这是我的 views.py 文件:
from django.shortcuts import render
def home(request, x)
context = {'x': x}
return render(request, 'home.html', context)
这是我的 urls.py 文件:
from django.conf.urls import patterns, include, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^home', views.home, name='home'),
)
这是我的 home.html 文件:
<html>
<body>
The value is: {{ x }}
</body>
</html>
最后,这是我的 index.html 文件:
<html>
<form method="post" action=???>
<input type="button" value="Click Me">
</form>
有人能告诉我我需要写什么来代替上面的 action 属性中的 ??? 吗?我试过设置??? = "{% url 'home' 123 %}"但这给了我一个“NoReverseMatch”错误。因此,我怀疑我的 urls.py 文件也可能有问题......
谢谢!
请您参考如下方法:
像这样重写你的 index.html
<html>
<form method="post" action=/home>
<input type="hidden" name="my_value" value="123">
<input type="button" value="Click Me">
</form>
它包含一个名为 my_value 的隐藏变量,它保存您的值 123。我的 view.py 像这样接受这个值,
from django.shortcuts import render
def home(request)
x = ' '
if request.POST:
x = request.POST['my_value']
context = {'x': x}
return render(request, 'home.html', context)
