Django Generic DetailView without a PK or Slug

By default the generic DetailView expects you to provide a pk or slug in the URL. If it’s missing you’ll get a lovely little error:

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

For the most part this is fine as you’ll usually provide an identifier in the URL. But what if you need to pull the identifier from someplace else such as the session?

To accomplish this, simply override the get_object method:

class UserView(DetailView):
template_name = 'template.html'
#model = User
#context_object_name = 'foo'
def get_object(self):
return get_object_or_404(User, pk=request.session['user_id'])

view raw

hosted with ❤ by GitHub

Also note that the model is no longer necessary as you’re explicitly calling it in get_object. The object is now available in the template using the model name, in this case user:

{{ }}

view raw


hosted with ❤ by GitHub

You can override this name by using context_object_name.

6 thoughts on “Django Generic DetailView without a PK or Slug”

  1. Thankyou for your tutorial…
    we work with this…

    class Dashboard_Member(generic.DetailView):
    	model = models.Member
    	template_name = "dashboard_member.html"
    	def get_object(self):
    		return get_object_or_404(User,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s