alternative to {% if request.user.is_active %} in Django Templates

1.7k views Asked by At

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.

2

There are 2 answers

1
defuz On BEST ANSWER

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.

1
Serhii Holinei On

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))