#python #django
#python #django
Вопрос:
Может кто-нибудь, пожалуйста, помочь мне решить эту проблему локальная переменная ‘intent’, на которую ссылаются перед назначением, я не мог выяснить, почему срабатывает client_secret в контексте. насколько мне известно, если код в операторе if завершается с ошибкой, тогда будет выполнен блок else, но я установил оператор print, и он также не отображается в teminal. если кто-нибудь может, пожалуйста, помогите мне в решении этой проблемы.
from django.shortcuts import render, redirect, reverse
from django.contrib import messages
from django.conf import settings
from .forms import OrderForm
from .models import Order, OrderLineItem, ProductLineItem, ExerciseLineItem, NutritionLineItem
from merchandise.models import Product
from exercise.models import ExercisePlans
from nutrition.models import NutritionPlans
from cart.contexts import cart_contents
import stripe
def checkout(request):
stripe_public_key = settings.STRIPE_PUBLIC_KEY
stripe_secret_key = settings.STRIPE_SECRET_KEY
if request.method == 'POST':
cart = request.session.get('cart', {
'merchandise_dic': {},
'excercise_plans_dic': {},
'nutrition_plans_dic': {},
})
form_data = {
'full_name': request.POST['full_name'],
'email': request.POST['email'],
'phone_number': request.POST['phone_number'],
'country': request.POST['country'],
'postcode': request.POST['postcode'],
'town_or_city': request.POST['town_or_city'],
'street_address1': request.POST['street_address1'],
'street_address2': request.POST['street_address2'],
'county': request.POST['county'],
}
order_form = OrderForm(form_data)
if order_form.is_valid():
print("Order form is valid")
order = order_form.save()
for product_type, dic in cart.items():
if product_type == 'merchandise_dic':
for item_id, quantity in dic.items():
print(f"This is item id of merchandise: {item_id}")
print(f"This is quantity of merchandise: {quantity}")
product = Product.objects.get(id=item_id)
print(product)
order_line_item = ProductLineItem(
order=order,
product=product,
quantity=quantity,
)
order_line_item.save()
elif product_type == 'excercise_plans_dic':
for item_id, quantity in dic.items():
print(f"This is item id of exercise plan: {item_id}")
print(f"This is quantity of exercise plan: {quantity}")
product = ExercisePlans.objects.get(id=item_id)
print(product)
order_line_item = ExerciseLineItem(
order=order,
product=product,
quantity=quantity,
)
order_line_item.save()
elif product_type == 'nutrition_plans_dic':
for item_id, quantity in dic.items():
print(f"This is item id of nutrition plan: {item_id}")
print(f"This is quantity of nutrition plan: {quantity}")
product = NutritionPlans.objects.get(id=item_id)
print(product)
order_line_item = NutritionLineItem(
order=order,
product=product,
quantity=quantity,
)
order_line_item.save()
else:
print("Order form is invalid")
messages.error(request, ('There was an error with your form. '
'Please double check your information.'))
return redirect(reverse('checkout'))
else:
print("Order form is invalid")
cart = request.session.get('cart', {
'merchandise_dic': {},
'excercise_plans_dic': {},
'nutrition_plans_dic': {},
})
if not cart:
messages.error(request,
"There is nothing in your
shopping cart at the moment")
return redirect(reverse('products'))
""" Got total from cart_contents """
current_cart = cart_contents(request)
current_total = current_cart['total']
stripe_total = round(current_total * 100)
""" Set secret key on stripe """
stripe.api_key = stripe_secret_key
""" Created payment intent """
intent = stripe.PaymentIntent.create(
amount=stripe_total,
currency=settings.STRIPE_CURRENCY,
)
print(intent)
order_form = OrderForm()
if not stripe_public_key:
messages.warning(request, 'Stripe public key is missing.
Did you forget to set it in your environment?')
template = 'checkout/checkout.html'
context = {
'order_form': order_form,
'stripe_public_key': stripe_public_key,
'client_secret': intent.client_secret,
}
return render(request, template, context)
Комментарии:
1. Что вы получаете, когда распечатываете intent?
2. Вам нужно инициализировать что-
intent
то, прежде чем переходить кif
оператору, который устанавливает его только в одной ветке!
Ответ №1:
Если ваш метод == «POST»: имеет значение true, то переменной intent не присваивается никаких параметров.
context = { ‘order_form’: order_form, ‘stripe_public_key’: stripe_public_key, ‘client_secret’: intent.client_secret, } Следовательно, intent в последнем разделе ничего не присваивается.
Ответ №2:
else:
print("Order form is invalid")
cart = request.session.get('cart', {
'merchandise_dic': {},
'excercise_plans_dic': {},
'nutrition_plans_dic': {},
})
if not cart:
messages.error(request,
"There is nothing in your
shopping cart at the moment")
return redirect(reverse('products'))
""" Got total from cart_contents """
current_cart = cart_contents(request)
current_total = current_cart['total']
stripe_total = round(current_total * 100)
""" Set secret key on stripe """
stripe.api_key = stripe_secret_key
""" Created payment intent """
---> intent = stripe.PaymentIntent.create(
amount=stripe_total,
currency=settings.STRIPE_CURRENCY,
)
print(intent)
order_form = OrderForm()
intent
назначается внутри else
блока, но на него ссылаются вне else
блока
context = {
'order_form': order_form,
'stripe_public_key': stripe_public_key,
---> 'client_secret': intent.client_secret,
Поэтому, если else
блок не выполняется intent
, переменной нет.
Ответ №3:
Спасибо всем за ваш ценный вклад, я нашел проблему и исправил ее. На самом деле я ничего не возвращал, если форма действительна! Таким образом, мне не хватало перенаправления на страницу checkout_success на первом уровне цикла for перед 1-м другим. Вот почему, даже если форма действительна, она все еще пытается вернуть оператор render () внизу, который вызывал эту ошибку. Таким образом, я создал представление checkout_success, а также checkout_success.html и перенаправляется на него. вот так и исправлена эта ошибка. возвращает перенаправление (обратное (‘checkout_success’, args=[order.order_number]))