Я пытаюсь отправить чековый платеж, используя python / django / jquery, но безуспешно. Я не уверен, в чем проблема, так как я использую ту же функцию проверки из курса, который я делаю. Поэтому print(order_form.is_valid(), payment_form.is_valid())
дает мне результат True, False
, в котором форма payment_form недействительна.
следуйте коду
checkout / views.py
from django.shortcuts import render, get_object_or_404, reverse, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import MakePaymentForm, OrderForm
from .models import OrderLineItem
from django.conf import settings
from django.utils import timezone
from tour_store.models import Destinations
import stripe
# Create your views here.
stripe.api_key = settings.STRIPE_SECRET
@login_required()
def checkout(request):
if request.method == "POST":
# call the two forms that will be used
order_form = OrderForm(request.POST)
payment_form = MakePaymentForm(request.POST)
# Then will check if both forms are valid if yes, save
print(order_form.is_valid(), payment_form.is_valid())
if order_form.is_valid() and payment_form.is_valid():
order = order_form.save(commit=False)
order.date = timezone.now()
order.save()
cart = request.session.get('cart', {})
total = 0
for id, quantity in cart.items():
destination = get_object_or_404(Destinations, pk=id)
total += quantity * destination.price
order_line_item = OrderLineItem(
order=order,
destination=destination,
quantity=quantity
)
order_line_item.save()
try:
customer = stripe.Charge.create(
amount=int(total * 100),
currency="EUR",
description=request.user.email,
card=payment_form.cleaned_data['stripe_id'],
)
except stripe.error.CardError:
messages.error(request, "Your card was declined!")
if customer.paid:
messages.error(request, "You have successfully paid")
request.session['cart'] = {}
return redirect(reverse('destination'))
else:
messages.error(request, "Unable to take payment")
else:
messages.error(request, "We were unable to take a payment with that card!")
else:
payment_form = MakePaymentForm()
order_form = OrderForm()
return render(request, "checkout.html", {"order_form": order_form, "payment_form": payment_form, "publishable": settings.STRIPE_PUBLISHABLE})
оформить заказ / формы
from django import forms
from .models import Order
class MakePaymentForm(forms.Form):
MONTH_CHOICES = [(i, i) for i in range(1, 12)]
YEAR_CHOICES = [(i, i) for i in range(2019, 2036)]
credit_card_number = forms.CharField(label='Credit card number', required=False)
cvv = forms.CharField(label='Security code (CVV)', required=False)
expiry_month = forms.ChoiceField(label='Month', choices=MONTH_CHOICES, required=False)
expiry_year = forms.ChoiceField(label='Year', choices=YEAR_CHOICES, required=False)
stripe_id = forms.CharField(widget=forms.HiddenInput)
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = (
'full_name', 'phone_number', 'country', 'postcode',
'town_or_city', 'street_address1', 'street_address2',
'county'
)
оформить заказ / шаблоны / оформить заказ. html
{% extends "base.html" %}
{% load static %}
{% load bootstrap_tags %}
{% block content %}
<div class="container">
<div class="row row-flex">
{% for item in cart_items %}
<div class="col-xs-10 col-xs-offset-1 col-sm-offset-0 col-sm-6 col-md-4 display panel panel-default">
<div class="panel-body">
<div class="product" src="{{ item.destination.image.url}}"></div>
<div class="caption">
<h3>{{ item.destination.tour_title }}</h3>
<p class="product-description">{{ item.destination.description|slice:":100" }}</p>
<p>€ {{item.destination.price}}</p>
</div>
</div>
</div>
{% endfor %}
</div>
<div class="row">
<p>Total</p>
<p><span class="glyphicon glyphicon-euro" aria-hidden="true"></span>{{ total }}</p>
</div>
<form role="form" method="post" id="payment-form" action="{% url 'checkout' %}">
{% csrf_token %}
<legend>Payment Details</legend>
<div id="credit-card-errors" style="display: none;">
<div id="alert-message block-message error" id="stripe-error-message"></div>
</div>
<div class="form-group col-md-6">
{{ order_form | as_bootstrap }}
</div>
<div class="form-group col-md-6">
{{ payment_form | as_bootstrap }}
</div>
<div class="form-group col-md-12">
<input class=" btn btn-primary" id="submit_payment_btn" name="commit" type="submit" value="Submit Payment">
</div>
</form>
</div>
<!-- head_js is a stripe requirement -->
{% block head_js %}
<script type="text/javascript" src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
//<![CDATA[
Stripe.publishableKey = '{{ publishable }}';
//]]>
</script>
<script type="text/javascript" src="{% static 'js/stripe.js' %}"></script>
{% endblock head_js %}
{% endblock %}
js / stripe. js
$(function() {
$("#payment-form").submit(function() {
var form = this;
var card = {
number: $("#id_credit_card_number").val(),
expMonth: $("#id_expiry_month").val(),
expYear: $("#id_expiry_year").val(),
cvc: $("#id_cvv").val()
};
Stripe.createToken(card, function(status, response) {
if (status === 200) {
$("#credit-card-errors").hide();
$("#id_stripe_id").val(response.id);
// Prevent the credit card details from being submitted
// to our server
$("#id_credit_card_number").removeAttr('name');
$("#id_cvv").removeAttr('name');
$("#id_expiry_month").removeAttr('name');
$("#id_expiry_year").removeAttr('name');
form.submit();
} else {
$("#stripe-error-message").text(response.error.message);
$("#credit-card-errors").show();
$("#validate_card_btn").attr("disabled", false);
}
});
return false;
});
});
Я пробовал все, кроме go, и единственная проблема, о которой я знаю, это то, что payment_form
не работает. Спасибо.