我正在尝试创建一个Web应用程序,用户将选择一个文件,进行数据处理,然后使用url参数(?status = 1)重定向到确认页面,如何从处理视图移至确认视图,然后显示确认页面?
我在下面放置了我的代码,这些代码在我的视图和url 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'),
]
最佳答案
我觉得您的代码中存在两个问题:
缩进在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))
在处理视图中尝试使用“ HttpResponseRedirect()”代替“ redirect(reverse())”来调用确认页面视图,如下所示:
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.
如果没有渲染模板,就无法期望页面显示出来。
关于python - Django工作流程从一个 View 重定向到另一个 View ,并显示带有url参数的页面,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34369849/