I overrided django admin login page and would like to pass some variables to the login p开发者_运维问答age. How can I do that?
One solution is to use extra_context parameter (Django 1.3 and newer).
from django.contrib.auth.views import login
...
return login(request, template_name, extra_context={
'template_variable':value
})
See these similar questions and answers:
- Adding extra_context in Django logout built-in view
- passing additional arguments to django's login & template
And the original feature ticket:
- Ticket #5298: The extra_context keyword argument...
Update: let me make it clear that I personally think you should write your own login view if you want to influence the context, namely because it's so simple (you can copy and paste the ~20 lines to your own view).
Since what I like to do on stackoverflow is find a way around anyways, here's a hacky alternative:
If you want to use the built in admin page the only method I see is to attach properties to AuthenticationForm
.
Here's django.contrib.auth.views.login
:
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm):
....
return render_to_response(template_name, {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}, context_instance=RequestContext(request))
The only place we can 'hitch a ride' into the login template while positively not affecting anything else is through AuthenticationForm
.
from django.contrib.auth.forms import AuthenticationForm
AuthenticationForm.foobar = 'Hello'
...
(r'^accounts/login/$', 'django.contrib.auth.views.login', \
{'authentication_form':AuthenticationForm),
# template
{{ form.foobar }}
Another alternative is to use a context processor, which injects variables into every view that uses RequestContext
. Use this if your variable has some use in other templates as well.
For clarity (I commented on Akseli's answer) another solution is to pass the extra template variables directly along from url.conf
via the extra_context
key:
# url.conf -- this example from older django versions refer to docs
from django.contrib.auth.views import login
urlpatterns = patterns('',
url(
r'^accounts/login/$',
login,
{
'template_name': 'login.html',
'extra_context': {
# Your extra variables here as key value pairs.
'title': 'My Page | Log In'
}
},
name='login'
),
... # other patterns
)
Like Akseli said, use extra_context, but pass the extra context as part of the context:
def login(...):
...
some_var = some_var.objects.all()
extra_context = {'some_var': some_var,}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context, current_app=current_app)
you can add your custom attribute to the request
which is available in the template i.e.
request.my_params = {
'my_param1':'my_param1',
'my_param2':'my_param2',
}
精彩评论