10

I currently have a DetailView for Django's built-in User.

url( r'^users/(?P<pk>\d+)/$', DetailView.as_view( model = User, template_name = 'doors/users/detail.html' ), name = 'users_detail' ) 

But when I access user in the template, it brings up the current logged in user, not the user with the pk that I pass from DetailUser. Do I need to tell DetailUser to rename the user variable to something else? And if so, how do I do that?

1 Answer 1

13

The django.contrib.auth.context_processors.auth sets the {{ user }} template context variable to either request.user or AnonymousUser. So, it overrides the {{ user }} context variable created by your DetailView:

def auth(request): """ Returns context variables required by apps that use Django's authentication system. If there is no 'user' attribute in the request, uses AnonymousUser (from django.contrib.auth). """ # If we access request.user, request.session is accessed, which results in # 'Vary: Cookie' being sent in every request that uses this context # processor, which can easily be every request on a site if # TEMPLATE_CONTEXT_PROCESSORS has this context processor added. This kills # the ability to cache. So, we carefully ensure these attributes are lazy. # We don't use django.utils.functional.lazy() for User, because that # requires knowing the class of the object we want to proxy, which could # break with custom auth backends. LazyObject is a less complete but more # flexible solution that is a good enough wrapper for 'User'. def get_user(): if hasattr(request, 'user'): return request.user else: from django.contrib.auth.models import AnonymousUser return AnonymousUser() return { 'user': SimpleLazyObject(get_user), 'messages': messages.get_messages(request), 'perms': lazy(lambda: PermWrapper(get_user()), PermWrapper)(), } 

You can work around the issue by setting context_object_name. For example, this will enable the {{ user_object }} context variable, set to the user of the DetailView:

url( r'^users/(?P<pk>\d+)/$', DetailView.as_view( model = User, template_name = 'doors/users/detail.html', context_object_name = 'user_object' ), name = 'users_detail' ) 

Dig deeper, read the documentation for get_context_object_name().

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not 100% sure on this, but I had other generic views, and the variable is the name of the model. For example, if I did model = Poll in a ListView, then the variable becomes poll_list. The same in a DetailView gives a variable name of poll. Maybe this is something new in Django v1.4?
You are correct, I fixed the above answer. Thank you for your feedback !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.