我正在尝试创建一个Web应用程序,用户将选择一个文件,处理数据,然后重定向到带有url参数的确认页面(?status = 1)如何从处理视图移动到确认视图然后显示确认页面?
我把下面的代码放在我的视图和urls py文件
# views.py
def marketdata_processing(request):
if request.method == 'POST':
uploadform = forms.MyUploadForm(request.POST, request.FILES)
if uploadform.is_valid():
newdoc = models.UploadDocument(docfile=request.FILES['uploadfile'])
filename = request.FILES['uploadfile'].name
newdoc.save()
selecteddate = newdoc.getselecteddate() # Model method calculated
fileid = newdoc.pk
request.session['fileid'] = fileid
request.session['selecteddate'] = selecteddate
return redirect(reverse('views.confirm_input_details'))
else:
uploadform = forms.MyUploadForm()
# Render list page with the documents and the form
return render_to_response(
'mytemplate.html',
{'uploadform': uploadform},
context_instance=RequestContext(request)
)
def confirm_input_details(request):
fileid = request.session['fileid']
selecteddate = request.session['selecteddate']
msg = 'Proceed to import data for %s? \nFileID Being Imported is %s ' % (
selecteddate, fileid,)
url = reverse('views.confirm_input_details', kwargs={'status': 1})
return HttpResponseRedirect(url)
# urls.py
urlpatterns = [
url(r'', views.marketdata_processing, name='myapp/mytemplate.html'),
url(r'^\?status=(?P<status>[0-9]+)$',
views.confirm_input_details, name='myapp/myconfirmpage.html'),
]
答案 0 :(得分:1)
我认为代码中存在一些问题:
缩进是python代码中非常重要的事情。请确保'marketdata_processing'视图中if-else语句的缩进顺序正确。请注意,在您的代码中:
return render_to_response('mytemplate.html',
{'uploadform': uploadform},
context_instance=RequestContext(request))
将始终执行,因为它在else语句之外。你可能想在else下缩进它(如果有意义的话) - 就像这样:
else:
uploadform = forms.MyUploadForm()
return render_to_response('mytemplate.html',
{'uploadform': uploadform},
context_instance=RequestContext(request))
而不是'redirect(reverse())'在处理视图中尝试'HttpResponseRedirect()'来调用确认页面视图,如下所示:
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/?status=1') --> relative URL shown
将相对/绝对网址(两者都可以)放在上面。
最后,使用上下文参数在“confirm_input_details”视图中呈现您的确认页面模板,如下所示:
def confirm_input_details(request):
fileid = request.session['fileid']
selecteddate = request.session['selecteddate']
msg = 'Proceed to import data for %s? \nFileID Being Imported is %s ' % (selecteddate, fileid)
return render_to_response('confirmpage_template.html'),
{'fileid': fileid,
'selecteddate': selecteddate,
'msg': msg}, context_instance=RequestContext(request))
** P.S:坚持整洁的基础知识,它会起作用。您碰巧在同一视图中调用了confirm_input_details视图。据我所知,这可能会让你陷入无限循环。任何观点的简单概念是:
take input:request, parameters
--> process logic with parameters
--> render a specific template or call another url where a template is being rendered.
如果没有渲染模板,您不能指望页面显示。