1

我有一个 django,我正在尝试将一个对象存储在 django session 变量中,并尝试在重定向视图中访问它,但它显示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'],并得到上述错误。

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

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

{'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, 
}}
4

1 回答 1

-1

口译员永远不会到达这部分

request.session['response'] = response

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

尝试更换

if request.method == 'POST':

if request.POST:

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

于 2013-08-16T10:57:10.407 回答