I created an app for table ordering (basically like an ecommerce website) that has 3 models:
class Dish(model.Models):
some other fields()
class Cart(model.Models):
customer = models.ForeignKey(User)
session_key = models.CharField(max_length=40)
dish = models.ForeignKey(Dish)
order = models.ForeignKey(Order)
paid = models.CharField(max_length = 3, default = "No")
some other fields()
class Order(model.Models):
customer = models.ForeignKey(User)
session_key = models.CharField(max_length=40)
some other fields()
All the items that are added to the cart have a default field of "No", that turn to "Yes" once the payment has been done. If the user is authenticated, it populates the customer field for the cart item, otherwise it creates a session key with the following function:
def create_session(request):
session = request.session
if not session.session_key:
session.create()
return session
To process the payment, the application uses Square (similar to stripe). The following view takes care of it:
from square.client import Client
def square_payment(request):
# this view receives the necessary data such as order total and token via a POST request.
# I have omitted these details for the simplicity of the example
if request.method == "POST":
#create a client object to handle payment through Square
client = Client(access_token= "some access token",environment= "production")
body = {}
body['amount_money']['amount'] = "some amount"
# execute payment with the amount specified in body
result = client.payments.create_payment(body = body)
if result.is_success():
if request.user.is_authenticated:
order_object = Order.objects.create(customer = request.user)
Cart.objects.filter(customer = request.user, paid = "No").update(paid = "Yes")
else:
session = create_session(request)
order_object = Order.objects.create(session_key = session.session_key)
Cart.objects.filter(session_key = session.session_key, paid = "No").update(paid = "Yes")
elif result.is_error():
return JsonResponse({"Message":"Error"})
I tested everything many times and seemed to work fine until I tested it at a restaurant and the results that I got were quite mixed. The results were as follow:
#1) Everything worked as expected, the payment got through, the Order object was created and all cart items associated to that order were updated to paid = "Yes". #2) The payment got through, the order object was created but the cart items were not updated to paid "Yes". #3) The payment got through, but neither the Order object was created nor the cart items updated to paid = "Yes".
Not entirely sure what the issue is, but I would really appreciate it if someone could point me in the right direction.