Generic detail view ProductListView must be called with either an object pk or a slug in the URLconf

Viewed 44

can someone help me found the mistake with my code? I'm studing Django that's why can be possible that i made some stupid mistake or i forgot to write something. In my homepage i would like just to show a list of products but i immediately got this error!

I already checked the topics here in SoF but i didn't found a solution.

Models:

from django.db import models

class Manufacturer(models.Model):
    name = models.CharField(max_length=120)
    location = models.CharField(max_length=120)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.name


class Product(models.Model):
    manufacturer = models.ForeignKey(Manufacturer,
                                    on_delete=models.CASCADE,
                                    related_name="products")
    name = models.CharField(max_length=120)
    description = models.TextField(blank=True, null=True)
    photo = models.ImageField(blank=True, null=True)
    price = models.FloatField()
    shipping_cost = models.FloatField()
    quantity = models.PositiveSmallIntegerField()

    def __str__(self):
        return self.name

This is my views:

from django.views.generic.detail import DetailView
from django.views.generic.list import ListView

from .models import Product, Manufacturer


class ProductDetailView(DetailView):
    model = Product
    template_name = "products/product_detail.html"


class ProductListView(DetailView):
    model = Product
    template_name = "products/product_list.html"

and this is the urls of my app:

from django.urls import path
from .views import ProductListView, ProductDetailView

urlpatterns = [
    path('', ProductListView.as_view(), name="product-list"),
    path('products/<int:pk>/', ProductDetailView.as_view(), name="product-detail"),
]

Thanks for the help!

1 Answers

Your ProductListView inherits from a DetailView, not a ListView. You should inherit from a ListView:

from django.views.generic.list import ListView

# …

class ProductListView(ListView):
    model = Product
    template_name = "products/product_list.html"

The reason you got this error is because by default, a DetailView will need a primary key, or slug to select a specific item from the QuerySet. For a ListView that is of course not the case.

Related