What's new
  • Do not create multi-accounts, you will be blocked! For more information about rules, limits, and more, visit the Help Page Found a dead link? Use the report button!
  • If no files are available, please contact me or reply in the thread. I will update them immediately.

Django frontend detect if user is logged in

To detect if a user is logged in on the frontend in Django, you can use Django's built-in session and authentication framework. Here are some common approaches:

1. Using Django Template Tags

If you're using Django templates for rendering the frontend, you can directly use the {% if user.is_authenticated %} template tag to check if the user is logged in.

JavaScript:
{% if user.is_authenticated %}

    <p>Welcome, {{ user.username }}!</p>

    <a href="{% url 'logout' %}">Logout</a>

{% else %}

    <p>You are not logged in.</p>

    <a href="{% url 'login' %}">Login</a>

{% endif %}
2. Using JavaScript with JSON Data

If your frontend involves JavaScript (e.g., React, Vue, etc.), you can pass the user's authentication status to JavaScript via a Django view. Here's an example:

JavaScript:
Django View



from django.http import JsonResponse

from django.contrib.auth.decorators import login_required



def user_status(request):

    return JsonResponse({'is_logged_in': request.user.is_authenticated})

JavaScript

JavaScript:
fetch('/user-status/')

  .then(response => response.json())

  .then(data => {

    if (data.is_logged_in) {

      console.log('User is logged in');

    } else {

      console.log('User is not logged in');

    }

  });

3. Using CSRF Tokens for Logged-In Status

If you're using Django's csrf_token, you can assume the user is logged in if the backend accepts requests without issues. However, this requires that the user has been authenticated before accessing CSRF-protected routes.

4. Django REST Framework (DRF) with Tokens

If you're using Django REST Framework for APIs, you can use token-based authentication (e.g., JSON Web Tokens or session-based tokens). For example, include the token in the request and check its validity in your backend.

Example in DRF

JavaScript:
from rest_framework.decorators import api_view

from rest_framework.response import Response



@api_view(['GET'])

def user_status(request):

    return Response({'is_logged_in': request.user.is_authenticated})

Frontend Fetch Example

JavaScript:
fetch('/api/user-status/', {

  headers: {

    'Authorization': `Token ${localStorage.getItem('token')}`

  }

})

  .then(response => response.json())

  .then(data => {

    if (data.is_logged_in) {

      console.log('User is logged in');

    } else {

      console.log('User is not logged in');

    }

  });

5. Session Middleware

Ensure that django.contrib.sessions.middleware.SessionMiddleware is enabled in your MIDDLEWARE settings to manage user sessions.


---

Choose the method that best fits your p
roject's architecture and framework.
 
Last edited:
Back
Top