Reputation: 75
I am kind of a beginner and I'm doing an ecommerce web-site now and in views I have get_object_404 and parameters to go with it but I keep getting cannot unpack non-iterable int object with an id parameter. I searched the topic and mostly found same problem with pk and it didn't work with id(or maybe I couldn't make it work who knows). here's the code: views.py:
from django.shortcuts import render, get_object_or_404
from .models import *
from cart.forms import CartAddProductForm
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
context = {
'categories': categories,
'category': category,
'products': products,
}
return render(request, 'onlineshop/product/list.html', context)
def product_detail(request, id, slug):
product = get_object_or_404(Product, id, slug=slug)
cart_product_form = CartAddProductForm()
context = {
'product': product,
'cart_product_form':cart_product_form,
}
return render(request, 'onlineshop/product/detail.html')
urls.py:
from django.urls import path
from . import views
app_name = 'onlineshop'
urlpatterns = [
path('', views.product_list, name='product_list'),
path('<slug:category_slug>/', views.product_list,
name='product_list_by_category'),
path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail')
]
models.py:
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('onlineshop:product_list_by_category', args=[self.slug])
class Product(models.Model):
category = models.ForeignKey(
Category, related_name='product', on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'))
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('onlineshop:product_detail', args=[self.id, self.slug])
Upvotes: 0
Views: 87