2014-02-21 98 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)