D
D
Deft7272020-12-17 14:14:22
Django
Deft727, 2020-12-17 14:14:22

Django anonymous cart?

Tell me how to make a basket for anonymous users and add goods to the basket?

models.py

class Meta:
        verbose_name = 'Корзина'
        verbose_name_plural = 'Корзина'
    related_name='cart',on_delete=models.CASCADE)

    owner = models.ForeignKey('Customer',null=True, verbose_name='Владелец',on_delete=models.CASCADE)
    products = models.ManyToManyField(CartProduct,blank=True,related_name='related_cart')
    total_products = models.PositiveIntegerField(default=0)
    final_price = models.DecimalField(max_digits=10,default=0, decimal_places=2,verbose_name='Общая сумма')
    in_order= models.BooleanField(default=False)
    for_anonymoys_user= models.BooleanField(default=False)
    # add session key
    session_key = models.CharField(max_length=40,null=True,blank=True)
    def __str__(self):
        return str(self.id)

    # def save(self,*args,**kwargs):
    #     cart_data= self.products.aggregate(models.Sum('final_price'),models.Count('id'))
    #     if cart_data.get('final_price__sum'):
    #         self.final_price = cart_data.get('final_price__sum')
    #     else:
    #         self.final_price=0
    #     self.total_products = cart_data['id__count']

# cart.related_producr.all() продукты в корзине

class Customer(models.Model):

    class Meta:
        verbose_name = 'Покупатель'
        verbose_name_plural = 'Покупатели'
    user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE)
    phone = models.CharField(max_length=20, verbose_name='Номер телефона')
    adress = models.CharField(max_length=255, verbose_name='Адрес', null=True, blank=True)
    orders = models.ManyToManyField('Order', verbose_name='Заказы покупателя', related_name='related_order')

    def __str__(self):
        return "Покупатель: {} {}".format(self.user.first_name, self.user.last_name)


class Order(models.Model):

    class Meta:
        verbose_name = 'Заказ'
        verbose_name_plural = 'Заказы'

    STATUS_NEW ='new'
    STATUS_IN_PROGRESS='in_progress'
    STATUS_READY= 'is_ready'
    STATUS_COMPLETED= 'completed'
    STATUS_DEACTIVE='deactive'

    BUYING_TYPE_SELF= 'self'
    BUYING_TYPE_DELIVERY = 'delivery'

    STATUS_CHOICES= (
        (STATUS_NEW,'Новый заказ'),
        (STATUS_IN_PROGRESS,'Заказ в обработке'),
        (STATUS_READY,'Заказ готов'),
        (STATUS_COMPLETED,'Заказ выполнен'),
        (STATUS_DEACTIVE,'Заказ Отменен')
    )

    BUYING_TYPE_CHOICES=(
        (BUYING_TYPE_SELF,'Самовывоз'),
        (BUYING_TYPE_DELIVERY,'Доставка')
        )


    customer = models.ForeignKey(Customer, verbose_name='Покупатель', related_name='related_orders', on_delete=models.CASCADE)
    first_name = models.CharField(max_length=255, verbose_name='Имя')
    last_name = models.CharField(max_length=255, verbose_name='Фамилия')
    phone = models.CharField(max_length=20, verbose_name='Телефон')
    cart = models.ForeignKey(Cart, verbose_name='Корзина', on_delete=models.CASCADE, null=True, blank=True)
    adress = models.CharField(max_length=1024, verbose_name='Адрес', null=True, blank=True)
    otdel = models.CharField(max_length=20,verbose_name='Отделение', null=True, blank=True)
    status = models.CharField(
        max_length=100,
        verbose_name='Статус заказ',
        choices=STATUS_CHOICES,
        default=STATUS_NEW
    )
    buying_type = models.CharField(
        max_length=100,
        verbose_name='Тип заказа',
        choices=BUYING_TYPE_CHOICES,
        default=BUYING_TYPE_SELF
    )
    comment = models.TextField(verbose_name='Комментарий к заказу', null=True, blank=True)
    created_at = models.DateTimeField(auto_now=True, verbose_name='Дата создания заказа')
    order_date = models.DateField(verbose_name='Дата получения заказа', default=timezone.now)
    # add session
    session = models.ForeignKey(Session, on_delete=models.SET_NULL, blank=True, null=True)
    def __str__(self):
        return str(self.id)


views.py
class AddToCartView(CartMixin,View):
    def get(self,request,*args,**kwargs):

        product_slug= kwargs.get('slug')
        product= Product.objects.get(slug=product_slug)

        if request.user.is_authenticated:
            cart_product,created=CartProduct.objects.get_or_create(
                user=self.cart.owner,cart=self.cart,product=product
            )
            if created:
                self.cart.products.add(cart_product)
            recalc_cart(self.cart)
            messages.add_message(request,messages.INFO,'Товар добавлен в корзину')
            return redirect(product.get_absolute_url())

            
        else:
            return HttpResponseRedirect('/registration/')

class DeleteFomCartView(CartMixin,View):

    def get(self,request,*args,**kwargs):

        product_slug=kwargs.get('slug')
        product= Product.objects.get(slug=product_slug)
        cart_product=CartProduct.objects.get(
            user=self.cart.owner,cart=self.cart,product=product
        )
        self.cart.products.remove(cart_product)
        cart_product.delete()
        recalc_cart(self.cart)
        messages.add_message(request,messages.INFO,'Товар Удален')
        return HttpResponseRedirect('/cart/')

class CartView(CartMixin, View):

    def get(self, request, *args, **kwargs):
        category = Category.objects.all()
        context = {
            'cart': self.cart,
            'category': category
        }
        return render(request, 'cart.html', context)
cartmixins.py

class CartMixin(View):
    def dispatch(self,request,*args,**kwargs):
        if request.user.is_authenticated:
            customer = Customer.objects.filter(user=request.user).first()
            if not customer:
                customer= Customer.objects.create(
                    user=request.user
                )
            cart = Cart.objects.filter(owner=customer,in_order=False).first()
            if not cart:
                cart= Cart.objects.create(owner=customer)
        else:
            cart= Cart.objects.filter(for_anonymoys_user=True).first()
            if not cart:
                cart= Cart.objects.create(for_anonymoys_user=True)
        self.cart=cart
        self.cart.save()
        return super().dispatch(request,*args,**kwargs)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question