"Как получить уже существующую корзину пользователя в Django" - PullRequest
0 голосов
/ 04 июля 2019

"Я создаю приложение для корзины, когда пользователь регистрируется на веб-сайте и впервые входит в систему на веб-сайте, поэтому корзина создает после этого пользователя, добавляет элементы в корзину и удаляет элемент из корзины, но когда пользователь выходит из веб-сайта и снова входит в системувеб-сайт, поэтому снова создается новая корзина. "

" Я хочу проверить, что у пользователя уже есть корзина, и если у пользователя нет корзины, поэтому новая корзина создается, в противном случае у пользователя уже есть корзина, поэтому не создавайте новую корзину "

Models.py

class CartManager(models.Manager):
      def new_or_get(self,request):
          cart_id = request.session.get("cart_id",None)
          qs = self.get_queryset().filter(id=cart_id)
          if qs.count() == 1:
             new_obj = False
             cart_obj = qs.first()
            if request.user.is_authenticated and cart_obj.user is None:
               cart_obj.user = request.user
               cart_obj.save() 
         else:
              cart_obj = Cart.objects.new(user=request.user)
              new_obj = True
              request.session['cart_id'] = cart_obj.id
         return cart_obj , new_obj

     def new(self, user=None):
         user_obj = None
         if user is not None:
            if user.is_authenticated:
               user_obj = user
         return self.model.objects.create(user=user_obj)
class Cart(models.Model):
      user       = models.ForeignKey(User,null=True , blank=True , on_delete=models.CASCADE)
      product    = models.ManyToManyField(Product, blank=True)
      subtotal   = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
      total      = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
      updated    = models.DateTimeField(auto_now=True)
      timestamp  = models.DateTimeField(auto_now_add=True)
      objects    = CartManager()

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

VIEWS.py

def cart_home(request):
    cart_obj,new_obj = Cart.objects.new_or_get(request)
    return render(request,"cart/cart.html",{"cart":cart_obj})

"Я начинаю, когда пользовательУ меня нет корзины, поэтому они создают новую корзину, если у пользователя уже есть корзина, поэтому они ловят существующую корзину пользователя "

1 Ответ

0 голосов
/ 04 июля 2019

Думаю, проблема в том, что вы нигде не проверяете тележки, в которых уже есть пользователь. Чтобы вернуть корзину, нужно проверить, нет ли на ней корзин, которые указывают на аутентифицированного пользователя.

Я не могу легко это проверить, но это может дать вам несколько идей о том, как поступить. Сначала следует попытаться получить корзину от пользователя, затем вернуться к идентификатору сеанса и, наконец, создать корзину, если ничего ранее не найдено.

class CartManager(models.Manager):

    def new_or_get(self, request):
        try:
            # First try to get the cart based off the authenticated
            # user.
            cart = self.get(user=request.user)
        except self.model.DoesNotExist:
            # This should fail if the user is not authenticated or if
            # the user doesn't have a cart associated with their
            # account.
            pass
        else:
            # Since there is no guarantee that the session id is set
            # correctly, set it.
            request.session['cart_id'] = cart.id

            # Return the cart that is already found. Nothing further
            # needs to be done.
            return cart, False

        try:
            # Try to get the cart based of the id variable stored in
            # the `request.session`.
            cart = self.get(id=request.session['cart_id'])
        except (self.model.DoesNotExist, KeyError):
            # This will fail if there is no `cart_id` in the session or
            # if no cart is found.
            pass
        else:
            # If there is no user on the cart and the user is
            # authenticated add the user to the cart.
            if not cart.user and request.user.is_authenticated:
                cart.user = request.user
                cart.save()

            # Again, return the cart that was found. Nother further
            # needs to be done.
            return cart, False

        # This point will be reached if no cart is found from either
        # the authenticated user or the session id. Create a new cart
        # and return it.
        cart = self.new(request.user)
        request.session['cart_id'] = cart.id
        return cart, True

    def new(self, user=None):
        # If the user is an `AnonymousUser` (boolean value of True, but
        # not authenticated) then just set the variable to `None`.
        if user and not user.is_authenticated:
            user = None
        return self.create(user=user)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...