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 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'),
]
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()
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.