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
| Property | Logged In | Anonymous |
|---|---|---|
is_authenticated | True | False |
username | Their username | Empty string |
is_anonymous | False | True |
Key Takeaways
user.is_authenticatedreturns True if logged in, False if anonymous- Use
{% if user.is_authenticated %}in templates for conditional rendering - Django automatically passes
userto all templates via the context processor - Show different nav links based on auth status for good UX