【问题标题】:Django: Form Data Not Being Accessed to Store Data in SessionDjango:未访问表单数据以在会话中存储数据
【发布时间】:2012-08-02 05:41:00
【问题描述】:

views.py

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 }} 

我正在尝试将数据从“索引”页面传递到“结果”页面。在这种情况下,我想在结果页面上显示输入和提交的字符串。

我的表单有什么问题?

另外,我是否正确地形成了会话键:值?

【问题讨论】:

  • 但是你发帖到/results,不应该是{% url index %}之类的吗?

标签: django django-forms django-templates django-views django-sessions


【解决方案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 }}

足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 2012-08-17
    • 1970-01-01
    相关资源
    最近更新 更多