MultiValueDictKeyError - ошибка stripeToken Django - PullRequest
0 голосов
/ 22 апреля 2020

сообщение об ошибке, которое я получаю в моем шаблоне: - MultiValueDictKeyError at / checkout / 'stripeToken' - Кажется, я нигде не могу найти решение в Интернете. Я выделил области в коде, где происходит stripeToken. Буду признателен за любые предложения, так как я застрял в этом довольно давно!

views.py

import time 
import stripe

from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.shortcuts import render, HttpResponseRedirect
from django.urls import reverse



# Create your views here.

from users.forms import UserAddressForm
from carts.models import Cart
from .models import Order
from users.models import Profile, UserAddress, UserAddressManager
from .utils import id_generator

try:
    stripe_pub = settings.STRIPE_PUBLISHABLE_KEY
    stripe_secret = settings.STRIPE_SECRET_KEY
except Exception as e:
    raise NotImplementedError(str(e))
    # stripe_pub = "pk_test_AueCfYJ1QIxjLej496MIA43t00BNIWgUb6"

stripe.api_key = stripe_secret

def orders(request):
    context = {}
    template = "orders/user.html"
    return render(request, template, context)

@login_required
def checkout(request):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        return HttpResponseRedirect(reverse("cart"))

    try:
        new_order = Order.objects.get(cart=cart)
    except Order.DoesNotExist:
        new_order = Order()
        new_order.cart=cart
        new_order.user = Profile.objects.get(user=request.user)
        # new_order.user = Profile.objects.get(user=request.user)
        new_order.order_id = id_generator()
        new_order.save()
    except:
        return HttpResponseRedirect(reverse("cart"))

    try:
        address_added = request.GET.get("address_added")
    except:
        address_added = None

    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None


    current_addresses = UserAddress.objects.filter(user=request.user)
    billing_addresses = UserAddress.objects.get_billing_addresses(user=request.user)

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

    **if request.method == "POST":
        try:
            user_stripe = request.user.userstripe.stripe_id
            customer = stripe.Customer.retrieve(user_stripe)
        except:
            customer = None
            pass
        if customer is not None:
            token = request.POST['stripeToken']
            card = customer.cards.create(card=token)
            charge = stripe.Charge.create(
                  amount=2000,
                  currency="eur",
                  card=card,
                  customer=customer,
                  description="Charge for %s" %(request.user.username)
                )**
            print(card)
            print(charge)
if new_order.status == "Finished":
        del request.session['cart_id']
        del request.session['items_total']
        return HttpResponseRedirect(reverse("cart"))

    context = {
    "address_form": address_form,
    "current_addresses": current_addresses,
    "billing_addresses": billing_addresses,
    "stripe_pub": stripe_pub,
    }
    template = "orders/checkout.html"
    return render(request, template, context)

оформить заказ. html - область, которая также включает

<script>

{% block jquery %}

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


    jQuery(function($) {
        $('#payment-form').submit(function(event) {
        var $form = $(this);

        // Disable the submit button to prevent repeated clicks
        $form.find('button').prop('disabled', true);

        Stripe.card.createToken($form, stripeResponseHandler);

        // Prevent the form from submitting with the default action
        return false;
        });
    });



    function stripeResponseHandler(status, response) {
        // Grab the form:
        var $form = $('payment-form');

        if (response.error) {
            // show the errors on the form
            $form.find('.payment-errors').text(response.error.message);
            $form.find('button').prop('disabled', false);
        }   else {
            // response contains id and card, which contains additional card details
            var token = response.id;
            // Insert the token into the form so it gets submitted to the server
            **$form.append($('<input type="hidden" name="stripeToken" />').val(token));**
            // and submit
            $form.get(0).submit(); 
            }
    };

{% endblock %}
</script>

base. html - кодирование для включения javascript

<script>
    $(document).ready(function(){
      {% block jquery %}{% endblock %}
    });

    </script>

, если кому-то понадобится пересмотреть мой код для решения проблемы, сообщите мне!

...