Home > Software engineering >  ValueError at /cart/add_cart/1/ The view carts.views.add_cart didn't return an HttpResponse obj
ValueError at /cart/add_cart/1/ The view carts.views.add_cart didn't return an HttpResponse obj

Time:10-07

If I add a product to the cart once is fine and the carts are created. But if I add it again then the above error occurs. In addition, when trying to edit or delete the created cart, an error also occurs: "TypeError at /admin/carts/cartitem/3/change/ str returned non-string (type Product)"

I have Django project with follow modules: Model Product

from django.db import models
from category.models import Category
from django.shortcuts import reverse

class Product(models.Model):
    product_name = models.CharField(max_length=256, unique=True)
    slug = models.SlugField(max_length=256, unique=True)
    description = models.TextField(max_length=512, blank=True)
    price = models.IntegerField()
    images = models.ImageField(upload_to='photos/products') 
    stock = models.IntegerField() 
    is_available = models.BooleanField(default=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    create_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    def get_url(self):
        return reverse('store:product-detail', args=[self.category.slug, self.slug])
  

    def __str__(self):
        return self.product_name

Model Cart

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

class Cart(models.Model):
    cart_id = models.CharField(max_length=256, blank=True)
    date_added = models.DateField(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)
    quantity = models.IntegerField()
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.product

Carts views

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


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)  # get the product
    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('carts:cart-view')


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

Carts urls

from django.urls import path
from .views import cart_view, add_cart

app_name = 'carts'
urlpatterns = [
    path('', cart_view, name='cart-view'),
    path('add_cart/<int:product_id>/', add_cart, name='add-cart'),
]

And tags in html

{% url 'carts:add-cart' single_product.id %} {% url 'carts:add-cart' product.id %}

CodePudding user response:

It is just an Indentation issue. Remove return redirect('carts:cart-view') from except block and put it in view function as follow:

def add_cart(request, product_id):
    product = Product.objects.get(id=product_id)  # get the product
    try:
        #Logic 
    except Cart.DoesNotExist:
        #Logic
    try:
        #Logic
    except CartItem.DoesNotExist:
        #Logic
        
    return redirect('carts:cart-view')
  • Related