Opened 12 years ago
Closed 11 years ago
#20294 closed Uncategorized (fixed)
Problem with generic views when the model is called 'User'.
Reported by: | Owned by: | Zbigniew Siciarz | |
---|---|---|---|
Component: | Documentation | Version: | 1.5 |
Severity: | Normal | Keywords: | user generic views context variable |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Context
I have extended the Django User model in order to have a customized authentication.
And my model class is also called 'User'.
I am successfully using generic views default configuration for all models except for the 'User'.
According to the documentation, the context variable will be inferred from the model name.
But there seems to be an extra context variable called user, that is always present and provides information about the authenticated user, for which I could not find mention in the documentation of 1.5, but is described in 1.2 docs here:
https://docs.djangoproject.com/en/1.2/topics/auth/#authentication-data-in-templates
Problem
The following code does not work as expected:
- urls.py
... url(r'^user/(?P<pk>\d+)/$', DetailView.as_view( model = User ), name = 'user'), ...
- user_detail.html
{% if user %} <p>id : {{ user.id }}</p> <p>name : {{ user.name }}</p> <p>description : {{ user.description }}</p> <p>email : {{ user.email }}</p> ...
Instead of getting the details for the user with the corresponding pk (user.id) is present in the URL, the authenticated user details are always returned.
There is no warning in the logs about the override, of the user object retrieved from the database, by the authenticated user object within the template context variables namespace.
Workaround
The desired behavior is obtained after changing the context object name from the default 'user' to 'u', as follows:
- urls.py
... url(r'^user/(?P<pk>\d+)/$', DetailView.as_view( model = User, context_object_name = 'u' ), name = 'user'), ...
- user_detail.html
{% if u %} <p>id : {{ u.id }}</p> <p>name : {{ u.name }}</p> <p>description : {{ u.description }}</p> <p>email : {{ u.email }}</p> ...
This way I can obtain the details for any given user, by id.
Change History (5)
comment:1 by , 12 years ago
Keywords: | user generic views context variable added |
---|
comment:2 by , 12 years ago
Component: | Generic views → Documentation |
---|---|
Triage Stage: | Unreviewed → Accepted |
comment:3 by , 11 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:5 by , 11 years ago
Resolution: | → fixed |
---|---|
Status: | assigned → closed |
I think it's worth adding a mention in the generic views docs that TemplateResponse uses RequestContext by default and linking to https://docs.djangoproject.com/en/1.5/ref/templates/api/#subclassing-context-requestcontext which discusses how processors can overwrite existing context variables.