I have a problem on my store site, when I want to confirm my order, when I click on confirmation on the payment page, it gives this error instead.
the error
Internal Server Error: /verify/
Traceback (most recent call last):
File "C:UsersQKDesktopMAworkshop.venvLibsite-packagesdjangocorehandlersexception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:UsersQKDesktopMAworkshop.venvLibsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersQKDesktopMAworkshop.venvLibsite-packagesdjangoviewsgenericbase.py", line 104, in view
return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersQKDesktopMAworkshop.venvLibsite-packagesdjangoviewsgenericbase.py", line 143, in dispatch
return handler(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersQKDesktopMAworkshopcartviews.py", line 124, in get
order_id = request.session['order_id']
~~~~~~~~~~~~~~~^^^^^^^^^^^^
File "C:UsersQKDesktopMAworkshop.venvLibsite-packagesdjangocontribsessionsbackendsbase.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
I asked some people what should I do to solve my problem and they told me that I didn’t set the order_id in the session.
view.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
I couldn’t think of anything, I asked other people to try, but they couldn’t help me either
New contributor
Arsham is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.