Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user information in django templates

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

like image 905
River Tam Avatar asked Dec 04 '12 22:12

River Tam


People also ask

What is {% include %} in Django?

Usage: {% extends 'parent_template. html' %} . {% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it.

How do I access Django templates?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

How do I login as user in Django?

Django by default will look within a templates folder called registration for auth templates. The login template is called login. html . Create a new directory called templates and within it another directory called registration .

How does Django authentication work?

The Django authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do. Here the term authentication is used to refer to both tasks.


1 Answers

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

like image 185
user Avatar answered Oct 19 '22 17:10

user