In a Django web application, its often necessary to display different content or features to users based on their login status. This can be achieved by checking if a user is logged in or not directly within your Django templates. In this blog, will explore how to check a user’s login status and conditionally display content in Django templates.
Using Django Templates to Check User Login Status
Django templates are powerful tools for rendering dynamic content on your web pages. You can include Python-like logic within these templates to customize the user experience. To check if a user is logged in, follow these steps:
- Access the User Object: Django templates have direct access to the
user
object. This object represents the currently logged-in user, or it will be an instance of an anonymous user if no one is logged in. - Conditionally Display Content:
- If the User Is Logged In: Use the
{% if user.is_authenticated %}
template tag to conditionally display content for logged-in users. - If the User Is Not Logged In: Use the
{% if not user.is_authenticated %}
template tag to conditionally display content for users who are not logged in.
Example: Displaying Content Based on User Login Status
Let’s consider an example where you want to display a “Welcome” message to logged-in users and a “Please log in” message to users who are not logged in. Here’s how you can achieve this in a Django template:
<!DOCTYPE html>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
{% if user.is_authenticated %}
<h1>Welcome, {{ user.username }}!</h1>
<!-- Display user-specific content for logged-in users -->
{% else %}
<h1>Please log in to access this content.</h1>
<!-- Display content for users who are not logged in -->
{% endif %}
</body>
</html>
In this example, we use the {% if user.is_authenticated %}
template tag to display personalized welcome message for logged-in users. If the user is not logged in, the template displays a message encouraging them to log in.
Check our blog on Django Authentication.