1

how can I hide user name from login page with If-Statement. Im using this code to show the user name in the main page after login in, and it's working

{%if request.user.first_name%}{{request.user.first_name}}{%else%}{{user}}{%endif%}

but the problem is that it's shown in the login page too as "AnonymousUser". how can I hide this

Any Idea?

Sam
  • 95
  • 1
  • 14

3 Answers3

3

Firstly you should check if user is authenticated and if authenticated show the first_name or username else just give link to login and signup.

{% if user.is_authenticated %}
   {%if request.user.first_name%}
      {{request.user.first_name}}
   {%else%}
      {{request.user.username}}
   {%endif%}
{% else %}
  <a href="" >login</a>
  <a href="" >Signup</a>
{% endif %}
Astik Anand
  • 12,757
  • 9
  • 41
  • 51
2

You can use .is_authenticated [Django-doc] here:

{% if request.user.is_authenticated %} ... {% endif %}

For a user that is not authenticated (like an AnonymousUser) the check will fail.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

Check this out:

{% if user.is_authenticated %}{% endif %}

Related: How to check if a user is logged in (how to properly use user.is_authenticated)?

Kubas
  • 976
  • 1
  • 15
  • 34