Site icon StudyGyaan

How to Check If User is Logged In or Not in Django HTML Templates

Django Web Framework Tutorials

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:

  1. 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.
  2. Conditionally Display Content:

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.

Exit mobile version