2014-02-21 51 views
2

我想创建一个“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文件可能有问题...

谢谢!

回答

0

由于没有捕获与URL一起发送的123的url,您将得到NoReverseMatch错误。让我告诉你一个简单的方法:

您可以设定动作,就像这样:

action="/home/123" # or any integer you wish to send. 

并通过修改的主页网址作为匹配的URL PY该网址:

url(r'^home/(?P<x>\d+)/$', views.home, name='home') 

这将你在家庭网址(在这种情况下应该是一个整数)发送的任何参数传递给x。因此,x将显示在home.html的

2

重写你的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)