我正在尝试将数据(最终字典,用于测试我传递虚拟变量)从一种形式传递到另一种形式。它是一个多步形式。 为此,我使用request.session对象。但是当我从第一个表单发布后,当我到达第二个表单时,会话数据是无,当我打印会话密钥时,它似乎已经改变了。我使用默认的基于数据库的会话。 我的总体目标是将数据从form1传递给form2。如果还有任何其他建议,我也愿意尝试。
参考文件 - https://docs.djangoproject.com/en/dev/topics/http/sessions/ http://gregblogs.com/dealing-with-forms-a-beginners-look-into-django-forms-and-sessions/
Settings.py
INSTALLED_APPS = (
'django.contrib.sessions',
...
)
MIDDLEWARE_CLASSES = [
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
]
Views.py
def step1(request):
form = UploadPickFileForm(request.POST)
# Create form instance
print "Session{}".format(request.session._get_session_key())
if request.method == 'POST':
initial = {'text':request.session.get('text', None)}
form = UploadPickFileForm(request.POST, request.FILES, initial = initial)
if form.is_valid():
action = form.cleaned_data.get('action')
uploaded_file = form.cleaned_data.get('file')
extractor = get_upload_extractor_for_source(form.cleaned_data.get('source'))
print "Action{}".format(action)
if action == INGEST_ACTION:
uploaded_file = form.cleaned_data.get('file')
try:
ingestable_upload = extractor.get_ingestable_upload(uploaded_file)
context = {'ingestable_upload': ingestable_upload}
except ParseError as e:
return self.show_error(e)
request.session['text'] = form.cleaned_data.get('action')
tt = request.session.get('text', None)
request.session.modified = True # just to force session save
print "Session data{}".format(tt)
return HttpResponseRedirect(urlresolvers.reverse('step2'))
else:
form = UploadPickFileForm()
else:
print "form is INVALID {}".format(form.errors)
return render(request,'step1.html', {'form':form})
def step2(request):
print "Session{}".format(request.session._get_session_key())
form = MappedReleaseTitleForm(request.POST)
formset_class = formset_factory(MappedReleaseTitleForm, extra =0)
tt = request.session.get('text', None)
print "Session data{}".format(tt)
if request.method == 'POST':
formset = formset_class(data,initial=[{'title':'HHHH'}])
if formset.is_valid():
data = formset.cleaned_data
print "data is {}".format(data)
return render (request, 'step2.html', {'form':formset_class})
答案 0 :(得分:0)
可能django-formtools(https://django-formtools.readthedocs.io/en/latest/)是个不错的选择吗?特别是,表单向导在多个Web页面中分割表单"。
如果不必从头开始编写,它可能有助于解决您的问题!