Episode 28 of 32

Checking Login Status

Show different content based on whether the user is logged in — conditionally display login, logout, and create article links in the navbar.

Checking Login Status

The navbar should show different links depending on whether the user is logged in or not. Django makes this easy with user.is_authenticated.

In Templates

<!-- templates/base_layout.html -->
<nav>
    <a href="{% url 'articles:list' %}">Articles</a>
    {% if user.is_authenticated %}
        <a href="{% url 'articles:create' %}">New Article</a>
        <span>Welcome, {{ user.username }}</span>
        <form method="POST" action="{% url 'accounts:logout' %}" style="display:inline">
            {% csrf_token %}
            <button type="submit">Logout</button>
        </form>
    {% else %}
        <a href="{% url 'accounts:login' %}">Login</a>
        <a href="{% url 'accounts:signup' %}">Sign Up</a>
    {% endif %}
</nav>

In Views

def my_view(request):
    if request.user.is_authenticated:
        # User is logged in
        print(request.user.username)
    else:
        # Anonymous user
        print('Not logged in')

Key Properties

PropertyLogged InAnonymous
is_authenticatedTrueFalse
usernameTheir usernameEmpty string
is_anonymousFalseTrue

Key Takeaways

  • user.is_authenticated returns True if logged in, False if anonymous
  • Use {% if user.is_authenticated %} in templates for conditional rendering
  • Django automatically passes user to all templates via the context processor
  • Show different nav links based on auth status for good UX