Django和Stripe MultiValueDictKeyError at / checkout /“'stripeToken'”

时间:2015-11-13 03:12:15

标签: python django stripe-payments

    views.py
    from django.conf import settings
    from django.shortcuts import render
    from django.contrib.auth.decorators import login_required
    import stripe


    stripe.api_key = settings.STRIPE_SECRET_KEY

    # Create your views here.
    @login_required
    def checkout(request):
        publishKey = settings.STRIPE_PUBLISHABLE_KEY
        if request.method == 'POST':
            token = request.POST['stripeToken']
                try:
                stripe.Charge.create(
                    amount=1000,
                    currency="usd",
                    card=token,


                    description="Charge for test@example.com"
    )
            except stripe.CardError:
                # The card has been declined
                pass
            # Create the charge on Stripe's servers - this will charge the user's card

        context = {'publishKey': publishKey

                    }
        template = 'checkout.html'
        return render(request, template, context)



When i run my views.py gives me this error -    MultiValueDictKeyError at /checkout/
"'stripeToken'"

here is my checkout.py
MultiValueDictKeyError at /checkout/
"'stripeToken'"

这是我的checkout.py 请帮忙,我会很感激。 我正在建立一个网站,最终采取付款,但当我运行它我得到错误,我认为它来自views.py,但我不确定是想从一些djangonites或pythoners得到一些反馈谢谢

4 个答案:

答案 0 :(得分:0)

stripeToken中的请求密钥request.POSTPOST中不存在时,Django会引发this error。您可能需要查看您的{{1}}表单数据以了解您的请求。

答案 1 :(得分:0)

>>> from django.utils.datastructures import MultiValueDict as MVD
>>> data = MVD({'name': ['John'], 'email': ['j@yahoo.com']})
>>> data['name']
'John'
>>> data['email']
'j@yahoo.com'
  

这个类[MultiValueDict]的存在是为了解决烦人的问题   由cgi.parse_qs引发,它返回每个键的列表,甚至   虽然大多数Web表单都提交单个名称 - 值对。

  

cgi.parse_qs:解析作为字符串参数给出的查询字符串(application / x-www-form-urlencoded类型的数据)。数据返回为   一本字典。字典键是唯一的查询变量名称   值是每个名称的值列表。

现在有一个不存在的密钥:

>>> data['apple']
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/7stud/.virtualenvs/django186p34/lib/python3.4/site-packages/django/utils/datastructures.py", line 322, in __getitem__
    raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'apple'"

查看最后一行如何显示...MultiValueDictKeyError: "'apple'"?看看在上面的django控制台中创建的MultiValueDict中密钥'apple'是如何存在的?

看看你的写作:

request.POST['stripeToken']

你得到了类似的错误? request.POSTMultiValueDict,其中包含POST数据中的键/值对。错误是"stripeToken"不是MultiValueDict中的键,这意味着POST数据中没有键/值对,键'stripeToken'

如果数据来自html表单,则表示没有表单输入元素,其name属性设置为“stripeToken”,例如

<input type="text" name="stripeToken">

答案 2 :(得分:0)

我有同样的问题,问题的原因在checkout.html。我正在使用这个

 Stripe.setPublishableKey({{ publishkey }});

而不是

Stripe.setPublishableKey('{{ publishkey }}');

纠正它解决了我的错误

答案 3 :(得分:0)

刷新您的可发布和秘密的api密钥,删除所有测试数据,然后尝试在终端上应用打印令牌,以查看其是否真正通过了:

if 'stripeToken' in request.POST:   
        print(request.POST['stripeToken'])