Home > OS >  Why isn't the number gotten from this random code generator function not being saved on the DB?
Why isn't the number gotten from this random code generator function not being saved on the DB?

Time:12-08

I am trying to generate a random redeem code for when a user purchases one of my products.

The problem is that once the random code exists and the GetRandomRedeemCode function generates a new code, it won't get saved by Django in the DB. What could be the issue?

This is the code that gets called whenever a new order is placed:

def CompleteOrder(request):
    order_qs = Purchase.objects.filter(user=request.user, ordered=False)
    if order_qs:
        specific_order = order_qs[0]
        for order in specific_order.product_purchased.all():
            order.item.purchased_by.add(request.user)
        specific_order.ordered = True
        specific_order.total_price = specific_order.get_total()
        *specific_order.redeem_code = GetRandomRedeemCode()*
        specific_order.save()
        return redirect("OrderCompletedSuccessURL")

And this is the GetRandomRedeemCode() function that gets called to create a random code and to check if the random code is already in the DB, ie. uniqueness.

def GetRandomRedeemCode():
    random_num = str(random.randint(10000000,99999999))
    if Purchase.objects.filter(redeem_code=random_num).exists():
        GetRandomRedeemCode()
    else:
        return random_num

CodePudding user response:

You don't return the recursive call:

def GetRandomRedeemCode():
    random_num = str(random.randint(10000000, 99999999))
    if Purchase.objects.filter(redeem_code=random_num).exists():
        return GetRandomRedeemCode()  #            
  • Related