如何在django会话框架中存储对象

时间:2013-08-16 10:35:45

标签: django redirect httpresponse django-sessions

我有一个django,我正在尝试将对象存储在django会话变量中,并尝试在重定向视图中访问该对象,但其显示keyerror如下所示

def payment(request):
    if request.method == 'POST':
        form = CardForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            response = response_from_payment_gateway(data)
            request.session['response'] = response
            return HttpResponseRedirect(reverse('paygate:payment_success'))
    else:
        form = CardForm(initial={'number':'4242424242424242'})
    return render_to_response('payment_form.html',{'form': form})


def PaymentSuccess(request):
    print request.session['response'],"=================>"
    response = None
    return render_to_response("payment_success.html", {'response':response}, context_instance=RequestContext(request))

结果

Internal Server Error: /payment/success/
Traceback (most recent call last):
  File "/home/Envs/app/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/home/user/virtualenvironment/apps/app/payment/views.py", line 120, in PaymentSuccess
    print request.session['response'],"=================>"
  File "/home/Envs/app/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
    return self._session[key]
KeyError: 'response'

所以我从支付网关取回一个包含交易详情的响应对象,我试图将其保存在session framework variable response中,如上所述。

我正在尝试在重定向的视图response中访问名为PaymentSuccess的变量request.session['response'],并获得上述错误。

那么我们如何在django的sessions中发送/保存对象?

在上面,响应对象将具有以下形式

{'status': 'SUCCESS', 'response': <Charge charge id=ch_2OXdxxxxNVw at 0xb508e76cL> JSON: {
  "amount": 100, 
  "amount_refunded": 0, 
  "balance_transaction": "txxxn_xxxxxxxxO", 
  "captured": true, 
 "currency": "usd", 
  "customer": null, 
  "description": null, 
}}

1 个答案:

答案 0 :(得分:-1)

解释器永远不会到达这个部分

request.session['response'] = response

这意味着我们的表单无效或请求的方法不是POST

尝试替换

if request.method == 'POST':

if request.POST:

如果它不起作用,请将request.session ['response']设置为任何其他值,以确保会话框架不会被破坏。 你需要进一步调试,我100%确定这不是会话问题。