2012-10-03 62 views
3

編輯:
我希望'success_url'(即result.html)顯示從'form.process()''數據'。下面的代碼顯然不起作用。 任何人都可以請告訴我它有什麼問題或建議另一種方式來基本查看模板中的上下文'數據'(無論是在列表或字典的形式),即更好的方式來顯示數據後,已提交。
非常感謝提前。發送表單數據到模板

-- urls.py -- 
url(r'^$', view='main_view'), 
url(r'^result/$', view='result_view'), 

-- views.py -- 
class ResultView(TemplateView): 
    template_name = "result.html" 

class MainView(FormView): 
    template_name = 'index.html' 
    form_class = UserInputForm 
    success_url = 'result/' 

    def form_valid(self, form): 
     data = form.process() 
     return super(MainView, self).form_valid(form) 

    def get_context_data(self, **kwargs): 
     context = super(MainView, self).get_context_data(**kwargs) 
     context['data'] = data 
     return context 

main_view = MainView.as_view() 
result_view = ResultView.as_view() 

回答

9

據我瞭解你的問題,你想顯示在用戶提交的形式在結果視圖中的內容。那是對的嗎?

在這種情況下,get_context_data方法根本無法幫助您,因爲它只會將數據存儲在MainView中的當前上下文中。

FormView的form_valid方法將使HttpResponseRedirect成爲success_url。所以現在的問題是,我們如何才能將數據提供給這個觀點。

Django return redirect() with parameters中所述,最簡單的方法是將數據放入會話中。在result.html模板,你可以再訪問該數據作爲Django: accessing session variables from within a template?

這裏解釋是代碼:

class ResultView(TemplateView): 
    template_name = "result.html" 

class MainView(FormView): 
    template_name = 'index.html' 
    form_class = UserInputForm 
    success_url = 'result/' 

    def form_valid(self, form): 
     self.request.session['temp_data'] = form.cleaned_data 
     return super(MainView, self).form_valid(form) 

在result.html模板,那麼你可以訪問此TEMP_DATA這樣:

{{ request.session.temp_data }} 
+0

是!'會話'是我正在查找的內容。謝謝DanEEStar。 – DGT

+0

要添加:您需要'context_processors'中的'django.core.context_processors.request'才能使用它。 – SaeX

0

在上下文中查找get_context_data Django class-based view docs。重寫的方法返回的dict將被傳遞到模板中。

1

如上所示,您可以覆蓋get_context_data

例如,你可以這樣做以下:

def get_context_data(self, **kwargs): 
    context = super(MainView, self).get_context_data(**kwargs) 
    #set some more context below. 
    context['foo'] = bar 
    ... 
    return context 
+0

謝謝,kranthi,但是重寫'get_context_data'並不會讓我在'result.html'模板中獲得'foo',這正是我試圖實現的目標,除非有人知道更好的方式來顯示數據提交表單後提交給用戶。 – DGT

0

有一對夫婦的事情,可能是你的問題。首先,在form_valid()方法中,您在之前處理表格,您將該類別的父母稱爲form_valid()。此外,您不會將結果存儲在兩種方法獲取它的通用位置。嘗試像這樣:

def form_valid(self, form): 
    self.data = form.cleaned_data 
    return super(MainView, self).form_valid(form) 

def get_context_data(self, **kwargs): 
    context = super(MainView, self).get_context_data(**kwargs) 
    context['data'] = self.data 
    return context 
+0

謝謝,但對不起,似乎沒有工作。我得到「'MainView'對象沒有屬性'數據'」錯誤。此外,form.process()似乎沒有踢入。如果我嘗試打印它,我什麼也得不到。 – DGT

+0

什麼是process()?你想做什麼?也許你可以將form_valid的結果存儲在self.data中,並在get_context_data中使用它。 – pyriku

+0

我是django的新手,請耐心等待。 'UserInputForm'是一種表單,當用戶提交時,我希望用戶輸入/選擇的表單值(從textarea,下拉列表等)通過類中的方法,返回的值將顯示在模板('result.html')。前面提到的'過程'是指調用另一種方法。 – DGT