我的商店网站出现问题,当我想确认订单时,当我点击付款页面上的确认时,却出现此错误。
错误
Internal Server Error: /verify/
Traceback (most recent call last):
File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\views\generic\base.py", line 104, in view
return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\views\generic\base.py", line 143, in dispatch
return handler(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\QK\Desktop\MAworkshop\cart\views.py", line 124, in get
order_id = request.session['order_id']
~~~~~~~~~~~~~~~^^^^^^^^^^^^
File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\contrib\sessions\backends\base.py", line 53, in __getitem__
return self._session[key]
~~~~~~~~~~~~~^^^^^
KeyError: 'order_id'
[26/Jul/2024 09:38:14] "GET /verify/?Authority=000000000000000000000000000001476833&Status=OK HTTP/1.1" 500 83027
Not Found: /favicon.ico
[26/Jul/2024 09:38:14] "GET /favicon.ico HTTP/1.1" 404 5053
我问了一些人我应该怎么做才能解决我的问题,他们告诉我我没有在会话中设置 order_id。
视图.py
from django.shortcuts import render, redirect, get_object_or_404
from account.models import Address
from .models import Order, OrderItem, DiscountCode
from django.http import JsonResponse
from django.http import HttpResponse
from product.models import Product
from django.conf import settings
from django.views import View
from .cart_module import Cart
import requests
import json
class CartView(View):
def get(self, request):
cart = Cart(request)
return render(request, 'cart/cart.html', {'cart': cart})
class AddCartView(View):
def post(self, request, pk):
product = get_object_or_404(Product, id=pk)
quantity = request.POST.get('quantity')
cart = Cart(request)
cart.add(product, quantity, request)
return redirect('cart:cart')
class DeleteCartView(View):
def get(self, request, id):
cart = Cart(request)
cart.delete(id)
return redirect('cart:cart')
class OrderDetailView(View):
def get(self, request, pk):
order = get_object_or_404(Order, id=pk)
return render(request, 'cart/order.html', {'order': order})
class OrderCreationView(View):
def get(self, request):
cart = Cart(request)
order = Order.objects.create(user=request.user, total_price=cart.total())
request.session['order_id'] = order.id # ذخیره شناسه سفارش در جلسه
# ...
return redirect('cart:order-detail', order.id)
class ApplyDiscountView(View):
def post(self, request, pk):
code = request.POST.get('discount_code')
order_id = request.session.get('order_id') # استفاده از .get() برای جلوگیری از KeyError
if order_id is None:
# انجام اقدامات لازم در صورت عدم وجود 'order_id' در جلسه
return HttpResponse("Order ID not found in session.", status=400)
order = get_object_or_404(Order, id=order_id)
discount_code = get_object_or_404(DiscountCode, name=code)
# ...
#? sandbox merchant
if settings.SANDBOX:
sandbox = 'sandbox'
else:
sandbox = 'www'
ZP_API_REQUEST = f"https://{sandbox}.zarinpal.com/pg/rest/WebGate/PaymentRequest.json"
ZP_API_VERIFY = f"https://{sandbox}.zarinpal.com/pg/rest/WebGate/PaymentVerification.json"
ZP_API_STARTPAY = f"https://{sandbox}.zarinpal.com/pg/StartPay/"
amount = 1000 # Rial / Required
description = "ساعاتی بعد از خرید با شما برای انتخاب ظاهر محصول تماس گرفته میشود" # Required
phone = 'YOUR_PHONE_NUMBER' # Optional
# Important: need to edit for realy server.
CallbackURL = 'http://127.0.0.1:8000/verify/'
class SendRequestView(View):
def post(self, request, pk):
order = get_object_or_404(Order, id=pk, user=request.user)
address = get_object_or_404(Address, id=request.POST.get('address'))
order.address = f"{address.address} - {address.phone}"
order.save()
request.session['order_id'] = str(order.id)
data = {
"MerchantID": settings.MERCHANT,
"Amount": order.total_price,
"Description": description,
"Phone": request.user.phone,
"CallbackURL": CallbackURL,
}
data = json.dumps(data)
# set content length by data
headers = {'content-type': 'application/json', 'content-length': str(len(data))}
try:
response = requests.post(ZP_API_REQUEST, data=data, headers=headers, timeout=10)
if response.status_code == 200:
response = response.json()
if response['Status'] == 100:
return redirect(ZP_API_STARTPAY + str(response['Authority']))
else:
return JsonResponse({'status': False, 'code': str(response['Status'])})
return JsonResponse(response)
except requests.exceptions.Timeout:
return JsonResponse({'status': False, 'code': 'timeout'})
except requests.exceptions.ConnectionError:
return JsonResponse({'status': False, 'code': 'connection error'})
class VerifyView(View):
def get(self, request):
order_id = request.session['order_id']
if order_id is None:
return HttpResponse("Order ID not found in session.", status=400)
order = Order.objects.get(id=str(order_id))
data = {
"MerchantID": settings.MERCHANT,
"Amount": order.total_price,
"Authority": request.get("Authority"),
}
data = json.dumps(data)
# set content length by data
headers = {'content-type': 'application/json', 'content-length': str(len(data))}
response = requests.post(ZP_API_VERIFY, data=data, headers=headers)
if response.status_code == 200:
response = response.json()
if response['Status'] == 100:
order.is_paid = True
return {'status': True, 'RefID': response['RefID']}
else:
return {'status': False, 'code': str(response['Status'])}
return response
我想不出什么办法,我让其他人尝试,但他们也帮不了我
你好我的伊朗朋友:)
我认为这里最好使用“request.session.get('order_id')”而不是“request.session['order_id']”
尝试一下。 我希望您的错误能够得到修复。