'AttributeError at /cart type object 'Cart' has no attribute 'model'

class Cart(View):
    def get(self , request):
        customer_id = request.session['customer']
        cart = get_object_or_404(Cart, customer_id= customer_id)
        return render(request , 'cart.html')

I am not able to get the cart object



Solution 1:[1]

Your view is also named Cart, so it will use the view instead of your model. Normally views use a …View suffix, so you might want to rename the view to:

class CartView(View):
    def get(self , request):
        cart = get_object_or_404(Cart, customer_id=request.session['customer'])
        return render(request, 'cart.html', {'cart': cart})

You can also work with a DetailView [Django-doc] to simplify the view:

from django.views.generic.detail import DetailView

class CartView(DetailView):
    context_object_name = 'cart'
    template_name = 'cart.html'

    def get_object(self):
        return get_object_or_404(Cart, customer_id=self.request.session['customer'])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem