【发布时间】:2017-10-21 00:19:40
【问题描述】:
当我使用 Django 的开发服务器时,以下代码在本地工作,但我在使用 Nginx 和 Gunicorn 的生产中遇到间歇性错误。
views.py
def first_view(request):
if request.method == "POST":
# not using a django form in the template, so need to parse the request POST
# create a dictionary with only strings as values
new_post = {key:val for key,val in request.POST.items() if key != 'csrfmiddlewaretoken'}
request.session['new_post'] = new_mappings # save for use within next view
# more logic here (nothing involving views)
return redirect('second_view')
def second_view(request):
if request.method == 'POST':
new_post = request.session['new_post']
# ... more code below
# render template with form that will eventually post to this view
我有时会在发布到第二个视图后收到 KeyError。基于documentation on when sessions are saved,似乎应该保存会话变量,因为它是直接修改会话。另外,如果我使用提供错误页面的调试面板的 sessionid 并通过 Django 的 API 访问会话,我可以看到“new_post”会话变量
python manage.py shell
>>> from django.contrib.sessions.backends.db import SessionStore
>>> s = SessionStore(session_key='sessionid_from_debug_panel')
>>> s['new_post']
# dictionary with expected post items
我有什么遗漏吗?提前感谢您的帮助!
【问题讨论】:
-
这个变量由什么组成?
-
new_post 变量是我在字典理解中使用 request.POST QueryDict 创建的字典。值都是字符串。
-
对不起,我错过了 new_mappings 变量的名称?你确定它不是空白的吗?或者你错过了用它来代替 new_post?
标签: django python-3.x redirect post session-variables