Get user information in django templates

River Tam picture River Tam · Dec 4, 2012 · Viewed 74.9k times · Source

What's the best way to get user information from a django template?

For example, if I just want to:

  1. If the user is logged in, display "Welcome [username]"
  2. Otherwise, display the login button.

I'm using django-registration/authentication

Answer

user picture user · Apr 6, 2014

An alternate method for current Django versions:

{% if user.is_authenticated %}
    <p>Welcome, {{ user.get_username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}


Note:

  • Use request.user.get_username() in views & user.get_username in templates. Preferred over referring username attribute directly. Source
  • This template context variable is available if a RequestContext is used.
  • django.contrib.auth.context_processors.auth is enabled by default & contains the variable user
  • You do NOT need to enable django.core.context_processors.request template context processor.

Source : https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates