我有这个表单来收集用户的数据。输入数据后,我使用HttpResponseRedirect 保护免受刷新。问题是因为我没有为这个应用程序使用数据库, 我无法弄清楚如何呈现用户输入的数据。
目前我需要呈现的数据存储在cd中。那么我怎样才能在成功之后重定向用户 数据输入并将数据传递到另一个视图,然后呈现它?我可以将它传递给另一个类视图,但渲染它是问题, 因为数据是由MathsConfig传递的,而不是通过网址传递的。
谢谢,对不起,我是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']
答案 0 :(得分: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()的函数。尽管我建议您返回字典,但不论您想要哪种方式。