[Django]-Having trouble with user.is_authenticated in django template

62๐Ÿ‘

โœ…

If the auth context processor is enabled, then user is already in the template context, and you can do:

{% if user.is_authenticated %}

If you want to access request in the template, make sure you have enabled the request context processor.

In your question you are using render_to_response. Ever since Django 1.3, it has been better to use render instead of render_to_response. Using render_to_response with RequestContext(request) works in Django <= 1.9, but from Django 1.10 onwards you must use the render shortcut if you want the context processors to work.

return render(request, 'template/login.html', context)
๐Ÿ‘คAlasdair

7๐Ÿ‘

Be aware that since Django 1.10 the is_authenticated is decorated with @property and it behaviour differs.

For UNAUTHENTICATED user calling {{user.is_authenticated}} results:

CallableBool(True) (when on Django < 1.10 it was True)

For AUTHENTICATED user calling {{user.is_authenticated}} results:

CallableBool(False) (when on Django < 1.10 it was False)

If you need to pass e.g to your javascript value like true or falseyou can do it with applying filter |yesno:"true,false"

<script language="javascript"> 
var DJANGO_USER = "{{user.is_authenticated|yesno:"true,false"}}";
</script>
๐Ÿ‘คandilabs

Leave a comment