0

I am getting this error on my django project:

   Request Method: GET
   Request URL: http://127.0.0.1:8000/cart/
   Exception Type: AttributeError at /cart/
   Exception Value: 'Cart' object has no attribute 'get'

and here is carts.views.py:

from django.shortcuts import render, redirect, get_object_or_404
from store.models import Product
from .models import Cart, CartItem



# Create your views here.

def _cart_id(request):
    cart = request.session.session_key
    if not cart:
        cart = request.session.create()
    return cart

def add_cart(request, product_id):
    product = Product.objects.get(id=product_id)

    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id = _cart_id(request)
            )
        cart.save()
    
    try:
        cart_item = CartItem.objects.get(product=product, cart=cart)
        cart_item.quantity += 1
        cart_item.save()
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(
            product= product,
            quantity= 1,
            cart= cart,
        )
        cart_item.save()
    return redirect('cart')


def cart(request):
    return render(request, 'store/cart.html')

I tried:

  1. rewrite the name of class 'Cart'
  2. use objectDoesnotexist instead of DoesnotExit
  3. double check the names of the classes in models.py

I am not able to debug this error. I overlooked my codes many times, but cant able to understand where is the error being generated. Thanks in advance.

Edit:

models.py:

from django.db import models
from store.models import Product

# Create your models here.

class Cart(models.Model):
    cart_id         = models.CharField(max_length=250, blank=True)
    date_added      = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.cart_id

class CartItem(models.Model):
    product         = models.ForeignKey(Product, on_delete=models.CASCADE)
    cart            = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='cart')
    quantity        = models.IntegerField()
    is_active       = models.BooleanField(default=True)

    def __str__(self):
        return self.product

Edit: Full Traceback:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/cart/

Django Version: 3.2.3
Python Version: 3.9.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'category',
 'accounts',
 'store',
 'carts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "D:\greatkart\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\greatkart\env\lib\site-packages\django\utils\deprecation.py", line 119, in __call__
    response = self.process_response(request, response)
  File "D:\greatkart\env\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
    if response.get('X-Frame-Options') is not None:

Exception Type: AttributeError at /cart/
Exception Value: 'Cart' object has no attribute 'get'

Edit : urls.py :

from django.urls import path
from . import views

urlpatterns = [
    path('', views.Cart, name='cart'),
    path('add_cart/<int:product_id>/', views.add_cart, name='add_cart'),
]

10
  • 1
    Paste the Cart model Commented May 22, 2021 at 13:49
  • And please paste the actual exception tracelog. Commented May 22, 2021 at 13:50
  • You should consider using get_or_create. That would reduce the length of this view by at least half its size. Also the log indicates you're sending a GET request, but I am not sure to understand, if this view is supposed to create in the first place, use a POST request. Commented May 22, 2021 at 14:13
  • Please show us full traceback error. Commented May 22, 2021 at 14:20
  • models.py has been added. Commented May 22, 2021 at 14:20

2 Answers 2

1

I started using the "Model.objects.filter().first()" instead of the "Model.objects.get()" because of those errors.

You could try this:

 cart = Cart.objects.filter(cart_id=_cart_id(request).first()

 if not cart:
     new_cart = Cart(cart_id = _cart_id(request))
     new_cart.save()

This method gives you all objects with the correct "cart_id". With ".first()" you will convert the giving queryset into one object (You need to do this even if you just have one object in the querset)

Instead of this

    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id = _cart_id(request)
            )
        cart.save()
Sign up to request clarification or add additional context in comments.

Comments

0

Thank You Abdul Aziz Barakat:

@asdfasdf In path('', views.Cart, name='cart'), did you mean to write views.cart instead of views.Cart? (Note the capitalization, Cart is your model name and cart is the name of your view)... – Abdul Aziz Barkat 6 mins ago

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.