alternative to {% if request.user.is_active %} in Django Templates
-
06-07-2021 - |
Question
What are the logic alternatives about:
{% if request.user.is_active %}
If the view doesn't return render_to_response
with a dictionary with request
, the template doesn't works properly.
So, any ideas are welcome.
//edited
my motivation is: when you work with views from installed apps, that you don't have the opportunity to modify them.
Solution
Add django.contrib.auth.context_processors.auth
to TEMPLATE_CONTEXT_PROCESSORS
in your settings.py
.
Now your have user
variable in all your templates. So you can use this:
{% if user.is_active %}
See more in the docs: template context processors in settings, auth context processor.
OTHER TIPS
view.py:
def foo_view(request):
...
is_active = request.user.is_active
return render_to_response('template.html', {'is_active':is_active})
or context_processor:
def is_user_active(request):
return {'is_active': request.user.is_active}
or middleware:
class IsUserActive:
def process_template_response(self, request, response):
response.context['is_active'] = request.user.is_active
template.html:
{% if is_active %}
...
{% endif %}
But sincerely, I don't know why render_to_response does not satisfy you:
...
return render_to_response('template.html',
context_instance=RequestContext(request))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow