TypeError at /add-to-cart/1/

276 views Asked by At

my add to cart was working fine and when i retry few pages later it gaves me that error TypeError at /add-to-cart/1/ add_to_cart() missing 1 required positional argument: 'request'

My view:
def add_to_cart(LoginRequiredMixin, request, slug):
    item = get_object_or_404(Item, slug=slug)
    order_item, created = OrderItem.objects.get_or_create(
        item=item,
        user=request.user,
        ordered=False
    )
    order_qs = Order.objects.filter(user=request.user, ordered=False)
    if order_qs.exists():
        order = order_qs[0]
        # check if the order item is in the order
        if order.items.filter(item__slug=item.slug).exists():
            order_item.quantity += 1
            order_item.save()
            messages.info(request, "This item quantity was updated.")
            return redirect("core:order-summary")
        else:
            order.items.add(order_item)
            messages.info(request, "This item was added to your cart.")
            return redirect("core:order-summary")
    else:
        ordered_date = timezone.now()
        order = Order.objects.create(
            user=request.user, ordered_date=ordered_date)
        order.items.add(order_item)
        messages.info(request, "This item was added to your cart.")
        return redirect("core:order-summary")

  

my url:
urlpatterns = [
    path('add-to-cart/<slug>/', add_to_cart, name='add_to_cart'),
]


Not sure what went wrong, help please.
1

There are 1 answers

0
willeM_ Van Onsem On

You can not use the LoginRequiredMixin mixin [Django-doc] as parameter, this is a function, not a class. The Mixin is mixed in the method resolution order (MRO) of a class. You can use the @login_required decorator [Django-doc] on a function:

from django.contrib.auth.decorators import login_required

@login_required
def add_to_cart(request, slug):
    # …

You can also restrict the slug parameter to only match on valid slugs with:

urlpatterns = [
    path('add-to-cart/<slug:slug>/', add_to_cart, name='add_to_cart'),
]