2014-11-05 21 views
0

我使用Pyramid建立一個web應用程序,和我有兩個觀點,其中一個導致其他:金字塔:路由匹配和POST使用表單數據同時

config.add_route("new", "/workflow/new") 
config.add_route("next", "/workflow/{id}/next") 

new看法是真的非常簡單,只介紹了一個HTML表單作爲Jinja2 template爲用戶在一些信息填寫:

<form method="post" action="{{ request.route_url('next',id='') }}" > 
    <input type="text" name="id" value="Identifier" /> 
    ... 
    <input type="submit" name="next" value="Next" /> 
</form> 

這裏的問題就認爲形式的action:我該如何使用文本輸入字段的內容0,也許處理它一點,然後在路由請求中傳遞它?

請注意,在這種情況下,表單數據從new視圖傳遞到next視圖,並且應該保持不變。

回答

0

當窗體發佈,表格字段將在請求對象中可用,請參閱 http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/webob.html#request

我相信這也張貼到相同的URL(<form action="#" method="post">)是一個好主意,這樣就可以驗證表單。然後,您可以在表單有效時處理並重定向到下一個URL,否則重新創建表單,如果沒有,則返回錯誤。

因此,你的看法可能會結束這樣的事情;

from pyramid.httpexceptions import HTTPFound 
from pyramid.url import route_url 

def myview(request): 

    if request.method == 'POST': 
     # Validate the form data 
     if <form validates successfully>: 
      # Do any processing and saving here. 
      return HTTPFound(location = route_url('next', id=request.params['id'], request=self.request)) 
     else: 
      request.session.flash("The form isn't valid.") 

    # Do some stuff here to re-populate your form with the request.params 

    return { # globals for rendering your form } 

現在已經有很多的問題/解答解決這個,如How can I redirect after POST in Pyramid?

+0

那['HTTPFound()'](http://docs.pylonsproject.org/docs/pyramid/en/latest/ api/httpexceptions.html#pyramid.httpexceptions.HTTPFound)異常是否爲下一個路徑正確調用Jinja2渲染器? – Jens 2014-11-05 00:58:45

+0

它幾乎是重定向到一個新的URL,因此URLs視圖可調用將會運行。 – neRok 2014-11-05 01:13:48

+0

然後,我怎樣才能(作爲HTTPFound請求的一部分)將表單內容發佈到'next'視圖?只是設置.POST沒有工作,沒有它,我會在'next'視圖中收到一個'Not a form request';下一個視圖也需要看到這些數據。 (已編輯的問題) – Jens 2014-11-05 02:05:32