Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic detail view must be called with either an object pk or a slug

Tags:

django

I am receiving that error when I try to visit the detail page of my product model. I have the slug field in the url file, but it doesn't seem to matter.

Model

class Product(models.Model):
    product_name= models.CharField(max_length=30, blank=False, null=False, verbose_name="the product name")
    product_slug= models.SlugField(max_length=30, blank=False, null=False, verbose_name="the product slug")
    product_excerpt= models.CharField(max_length=100, blank=False, null=False, verbose_name="product excerpt")
    def _set_product_code(self):
        product_code_temp = hashlib.sha224()
        product_hash = self.product_name
        product_hash = product_hash.encode('utf-8')
        product_code_temp.update(product_hash)
        return product_code_temp.hexdigest()[0:5]
product_code = property(_set_product_code)

View

class ProductPage(DetailView):
    model = Product
    context_object_name = 'product'
    template_name="product.html"

Url

url(r'^product/(?P<product_slug>\w+)/(?P<product_code>\w+)/$', ProductPage.as_view(), name="product"),

Can anyone pinpoint what I'm doing wrong?

like image 218
Iohannes Avatar asked Oct 16 '13 15:10

Iohannes


2 Answers

I would like to add that get_object could also be used in a case where we have a different look up parameter for primary key

Example, if I want to get my object by guid, which I am passing in my URLConf

def get_object(self):
    return Product.objects.get(guid=self.kwargs.get("guid"))
like image 60
akotian Avatar answered Oct 19 '22 10:10

akotian


Set the slug_field attribute on the view class:

class ProductPage(DetailView):
    model = Product
    slug_field = 'product_slug'

Depending on your URLConf you may also need to specify the name of the kwarg that corresponds to the slug. It defaults to 'slug'. If you used something different in the URL specification, such as 'product_slug' in this example, specify the slug_url_kwarg property on the view as well:

    slug_url_kwarg = 'product_slug'
    # etc
like image 34
Peter DeGlopper Avatar answered Oct 19 '22 09:10

Peter DeGlopper