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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']) |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{ user.id }} |
You can override this name by using context_object_name.
Thankyou for your tutorial…
we work with this…
Thanks, very good
How can i pass a user.name in url path?
Thanks! Exactly what I needed.
great thanks