[Django]-Django Using Slug Field for Detail URL

4đź‘Ť

âś…

You actually don’t need to define pk_url_kwarg at all, and in fact by doing so you have confused things leading to the object not being found.

As you can see from the default implementation of get_object, the view normally looks for either a pk or slug kwarg in the URL; whichever it finds will be used for the lookup. But by setting pk_url_kwarg to slug, you’re telling the view to get the URL kwarg named “slug” but use it to look up against the PK field, which obviously won’t work.

Just remove that attribute altogether, and Django will detect your slug kwarg and use it to correctly look up against the slug field.

Leave a comment