A
A
Alex Lukyanets2020-12-04 20:09:50
Django
Alex Lukyanets, 2020-12-04 20:09:50

How to implement anonymous user authentication?

I am developing a test project, an online store on Django.
At the moment, adding to the cart is possible only for an authorized user.
The model refers to the user of the model from the django box.

What is the best way to implement the functionality of a registered user and an anonymous user in the checkout process...?

Will carry out

class OrderProduct(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE, blank=True, null=True)
    ordered = models.BooleanField(default=False)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField(verbose_name='Количество', default=1)

    def __str__(self):
        return f"{self.quantity} of {self.product.name}"

    def get_total_item_price(self):
        return self.quantity * self.product.price

    def get_total_discount_item_price(self):
        return self.quantity * self.product.discount_price

    def get_total_amount_saved(self):
        return self.get_total_item_price() - self.get_total_discount_item_price()

    def get_final_price(self):
        if self.product.discount_price:
            return self.get_total_discount_item_price()
        return self.get_total_item_price()


class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    products = models.ManyToManyField(OrderProduct)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField()
    ordered = models.BooleanField(default=False)

    def __str__(self):
        return str(self.user)

    def get_total(self):
        total = 0
        for order_product in self.products.all():
            total += order_product.get_final_price()
        return total

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-12-04
@mynameiswisethanyesturday

options
1. store the cart on the client side in cookies, localstorage or wherever else you can
3. store the cart on the server side in request.session
2. make a model where instead of user, use sessionid

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question