Copy data from guest user Account and delete the guest user and send data to logged in or registered user with pure django

I'm currently working on an e-commerce website and the customer can order without logging in, but what I'm looking for is that after the customer add product to the cart, when they decide to Checkout must login or register. What I want is for the guest user account to be deleted and the card data to be transferred to the logged in or registered user account.

class Account(AbstractBaseUser):
""" My custom user manager """
phone_number            = models.CharField(unique=True, max_length=11, validators=[MinLengthValidator(11)], blank=True)
session_key             = models.CharField(max_length=40, null=True, blank=True)

USERNAME_FIELD = 'phone_number'



class OrderSummaryView(View):
def get(self, *args, **kwargs):
    try:
        order = Order.objects.get(user=self.request.user, ordered=False)
        context = {
            'object': order
        }
        return render(self.request, 'shop/ordersummary.html', context)
    except:

        """ here i can create Guest user account with session_key """

        session_key = self.request.COOKIES['sessionid']
        customer, created = Account.objects.get_or_create(session_key=session_key)

        order = Order.objects.get(user=customer, ordered=False)
        context = {
            'object': order
        }   
        return render(self.request, 'shop/ordersummary.html', context)



def CheckoutView1(request):

""" Here when the guest user wants to checkout, he/she has to login or register
    And when they log in I want to remove the guest account and send the data to 
    the logged in or registered account. """

if not request.user.is_authenticated:
        return redirect("login")

context = {}
if request.POST:
    form = CheckOutUpdateForm(request.POST, instance=request.user)
    if form.is_valid():
        form.save()
        return redirect('check_out2')
else:
    order = Order.objects.get(user=request.user, ordered=False)
    form = CheckOutUpdateForm(

        initial={

                "phone_number": request.user.phone_number, 
                "email": request.user.email, 
                "username": request.user.username,
                "first_name": request.user.first_name,
                "last_name": request.user.last_name,
                "street_address": request.user.street_address,
                "country": request.user.country,
                "zip": request.user.zip,
            }
        )



context['account_form'] = form
context['order'] = order


return render(request, "shop/checkout1.html", context)
Back to Top