2014-01-16 63 views
0

我有這種從用戶收集數據的表單。數據輸入後,我使用HttpResponseRedirect 來防止刷新。問題是因爲我沒有使用這個應用程序的數據庫, 我無法弄清楚如何渲染用戶輸入的數據。將數據呈現到模板並使用HttpResponseRedirect

目前需要渲染的數據存儲在cd中。那麼我怎麼能在成功輸入數據後重定向用戶並將數據傳遞給另一個視圖,然後再渲染它呢?我可以將它傳遞給另一個類視圖,但是呈現它是問題, 由於數據由MathsConfig傳遞而不是通過URL傳遞。

謝謝,對不起我是Django的新手。

代碼如下

views.py

class MathsConfig(View): 
    form_class = MathsForm 
    initial={'operation': "Addition", 
        'rows': "", 

        "between1": "1 - 99", 
        "between2": "1 - 99", 
        "between3": None, 
        "between4": None, 
        "between5": None, 

        "questions": 20, 
      } 
    template_name = 'maths/maths-config.html' 

    def get(self, request, *args, **kwargs): 
     form = self.form_class(initial=self.initial) 
     return render(request, self.template_name, {'form': form}) 

    def post(self, request, *args, **kwargs): 
     form = self.form_class(request.POST) 
     if form.is_valid(): 
      cd = form.cleaned_data 

      return HttpResponseRedirect(reverse('maths:maths_success')) 
     return render(request, self.template_name, {'form': form}) 


class MathsQuestions(object): 

    def __init__(self): 
     # want to pass cd varible here and then render it. 

class MathsSuccess(TemplateView): 
    template_name = "maths/maths-success.html" 

urls.py

urlpatterns = patterns('', 
    url(r'^config/$', views.MathsConfig.as_view(), name='maths_config'), 
    url(r'^success/$', views.MathsSuccess.as_view(), name='maths_success'), 
    url(r'^$', views.MathsQuestions(), name='maths_display'), 
) 

編輯:

class MathsQuestions(Object): 

    def __init__(self, request): 

     if 'entered_form_data' in request.session.keys(): 
      formdata = request.session['entered_form_data'] 
      del request.session['entered_form_data'] 

回答

2

儲存於會話。

request.session['entered_form_data'] = data 

而在接下來的觀點:

if 'entered_form_data' in request.session.keys(): 
    formdata = request.session['entered_form_data'] 
    del request.session['entered_form_data'] 

編輯:

def someview(request): 
    template = 'something.html' 

    form = SomeForm(request.POST) if request.method == 'POST' else SomeForm() 

    if request.method == 'POST': 
    if form.is_valid(): 
     data = form.get_cleaned_data() 
     request.session['entered_form_data'] = data 
     return HttpResponseRedirect('/someurl/') 

    render_to_response(template, {'form':form}, context_instance=RequestContext(request)) 

def someurl_view(request): 
    template = 'someurl.html' 

    render_to_response(template, {'formdata':request.session.pop('entered_form_data', None)}, context_instance=RequestContext(request)) 

,當然你需要創建一個函數,返回從形成自己的數據。我的意思是我稱之爲form.get_cleaned_data()的函數。不管你想要什麼,儘管我建議你返回字典。

+0

感謝您的回覆。我試圖添加這個,但我得到一個類型錯誤。再次,我是Django的新手,不確定正確的語法。請參閱上面的編輯我所嘗試的。 – user1831677

+0

您需要在視圖中進行數據存儲,而不是在表單中。我會更新答案。 –

+1

@OdifYltsaeb你的第二個片段可以被完全替換爲'formdata = request.session.pop('entered_form_data',None)' ' –