QueryDict不包含隐藏的表单字段,提供了MultiValueDictKeyError

时间:2019-06-16 14:21:03

标签: python django django-forms csrf hidden

我正在尝试将Razorpay付款网关与Django集成在一起。如何获得Razorpay在视图中自动发送的隐藏字段?

checkout / payment_details.html

<form action="{% url 'checkout:preview' %}" method="POST">
<!-- Note that the amount is in its subunit value = 599 -->
<script
    src="https://checkout.razorpay.com/v1/checkout.js"
    data-key="rzp_test_YYUUnrrBMW42iL"
    data-amount="{{ order_total_incl_tax_cents }}"
    data-currency="INR"
    data-buttontext="Pay with Razorpay"
    data-name="{{ shop_name }}"
    data-description="{{ basket.num_items }} items ({{ order_total.incl_tax|currency }})"
    data-image="https://your-awesome-site.com/your_logo.jpg"
    data-prefill.name="Gaurav Kumar"
    data-prefill.email="test@test.com"
    data-theme.color="#F37254"
></script>
<input type="hidden" value="{{ razorpay_token_form }}" name="razorpay_payment_id">
</form>

checkout / views.py

class PaymentDetailsView(CorePaymentDetailsView):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(PaymentDetailsView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        ctx = super(PaymentDetailsView, self).get_context_data(**kwargs)
        if self.preview:
            ctx['razorpay_token_form'] = forms.RazorpayTokenForm(self.request.POST)
            ctx['order_total_incl_tax_cents'] = (
                ctx['order_total'].incl_tax * 100
            ).to_integral_value()
        else:
            ctx['order_total_incl_tax_cents'] = (
                    ctx['order_total'].incl_tax * 100
            ).to_integral_value()
            ctx['razorpay_publishable_key'] = settings.RAZORPAY_PUBLISHABLE_KEY
        return ctx

    def handle_payment(self, order_number, total, **kwargs):
        print("requst in handle payment")
        print(self.request.GET)
        razorpay_ref = Facade().charge(
            order_number,
            total,
            card=self.request.POST['razorpay_payment_id', False],
            description=self.payment_description(order_number, total, **kwargs),
            metadata=self.payment_metadata(order_number, total, **kwargs))

        source_type, __ = SourceType.objects.get_or_create(name=PAYMENT_METHOD_RAZORPAY)
        source = Source(
            source_type=source_type,
            currency=settings.RAZORPAY_CURRENCY,
            amount_allocated=total.incl_tax,
            amount_debited=total.incl_tax,
            reference=razorpay_ref)
        self.add_payment_source(source)

        self.add_payment_event(PAYMENT_EVENT_PURCHASE, total.incl_tax)

堆栈跟踪

Traceback (most recent call last):
  File "C:\Users\kingmaker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\oscar\apps\checkout\views.py", line 580, in submit
    self.handle_payment(order_number, order_total, **payment_kwargs)
  File "C:\Users\kingmaker\workspace\blackweb_release_2.0\blackweb_services\checkout\views.py", line 44, in handle_payment
    card=self.request.POST['razorpay_payment_id', False],
  File "C:\Users\kingmaker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
    raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "('razorpay_payment_id', False)"

打印print(self.request.POST)给出

 <QueryDict: {'csrfmiddlewaretoken': ['jmeHeDEeNhaLM591S4113k1nNiXPLlPOT7eO47pqFyweLRw5al5ldrafTQmM9JPR'], 'action': ['place_order']}>

如何将Payment_id放入querydict?

1 个答案:

答案 0 :(得分:1)

表达式:

self.request.POST['razorpay_payment_id', False]

在这里没有多大意义。这意味着您查询的是2元组('razorpay_payment_id', False),但是据我所知,您只想将False用作“后备”值。

self.request.POST.get('razorpay_payment_id', False)

因此,我们在这里使用QueryDict.get(..) [Django-doc]函数,该函数带有两个参数:要搜索的键(此处为'razorpay_payment_id'),作为第二个参数,可选的默认值(如果键丢失则返回)( False)。

请注意,在模板中,您会在隐藏字段中呈现 form 。您应该改为渲染一个值,例如:

{{ razorpay_token_form }}
<input type="hidden" custom="Hidden Element" name="hidden">