1

views.pyDjango的:表單數據不被訪問的數據存儲在會話

from textize.models import Textizer 
from django.http import HttpResponseRedirect 
from django.shortcuts import render_to_response 
from django.core.context_processors import csrf 

def index(request): 
    if request.method == 'POST': 
     form = Textizer(request.POST) 
     print "debug 0" # <---It's not reaching this point when I submit the data via the form 
     if form.is_valid(): #check to see if the input is valid 
      print "debug 1" 
      request.session['text'] = form.cleaned_data['to_textize'] #set the session key:value pair 
      return HttpResponseRedirect('/results') #redirect to the results page 

    else: 
     form = Textizer() 
     print "debug 2" # reaches here 

    c = {'form': form} 
    c.update(csrf(request)) 

    return render_to_response('index.html', c) 

def results(request): 
    text = request.session.get("text", "dummy") 
    c = {'text' : text} 
    return render_to_response('results.html', c) 

的index.html

<form action="/results" method="POST"> {% csrf_token %} 
    {{ form.as_p }} 
    <input type="submit" value="Submit" /> 
</form> 

results.html

<b>Input text: </b>{{ text }} 

我'試圖將數據從「索引」頁面傳遞到「結果」頁面。在這種情況下,我想顯示在結果頁面上鍵入並提交的字符串。

我的表單出了什麼問題?

另外,我正在形成會話密鑰:值正確嗎?

+1

但是你發佈到'/結果',不應該像'{%url index%}'這樣的東西嗎? – okm 2012-08-04 11:14:10

回答

1
from textize.models import Textizer 
from django.http import HttpResponseRedirect 
from django.shortcuts import render_to_response 
from django.core.context_processors import csrf 

def index(request): 

    form = Textizer(request.POST or None) 

    if request.method == 'POST': 
     print "debug 0" 
     if form.is_valid(): 
      print "debug 1" 
      request.session['text'] = form.cleaned_data['to_textize'] 

    c = {'form': form, 'text':request.session.get("text", "")} 
    c.update(csrf(request)) 

    return render_to_response('index.html', c) 

然後模板的index.html

<form action="" method="POST"> {% csrf_token %} 
    {{ form.as_p }} 
    <input type="submit" value="Submit" /> 
</form> 
result: {{ text }} 

足以讓這是怎麼回事。