'In Django, how to restrict access to a template to users based on their department_name. Each user belongs to certain department

I have the below model. Departments, users. Users are assigned to a department. How can I restrict the access of templates based on the department_name of a user? For eg : User can view Application Template_1 if department_name == "Computer_Department". Here user belong to "computer" department. User can view Application Template_2 if department_name == "Electrical_Department". Here user belong to "electrical".

******My code are as below models.py

class Departments(models.Model):
    id = models.AutoField(primary_key=True)
    department_name = models.CharField(max_length=255) # here department name can be computer, electrical etc
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = models.Manager()

class Users(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
    department_id = models.ForeignKey(Departments, on_delete=models.DO_NOTHING, default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = models.Manager()

UserViews.py

def bi_powise(request):
    return render ( request, 'user_template/application_template/bi_powise.html', {})
    

urls.py

path ( 'bi_powise_user', UserViews.bi_powise, name = 'bi_powise_user' )

sidebar_template.html

      {% url 'bi_powise_user' as bi_powise_user %}
      <a href="{{ bi_powise_user }}" class="nav-link {% if request.path == bi_powise_user %} active {% endif %}">
        <i class="nav-icon fas fa-chalkboard"></i>
        <p>
          BI PO-Wise
        </p>
      </a>
    </li>

bi_powise.html

{% extends 'user_template/base_template.html' %}

{% block page_title %}
ANSwer BI PO-WISE  
{% endblock page_title %}

{% block main_content %}

    <!-- Main content -->
    <body>
      <section class="content">
      <center>
        <iframe width="1400" height="1300" src="https://app.powerbi.com/reportEmbed?reportId=****************************************" frameborder="0" allowFullScreen="true"></iframe>

      </center>
       
      <!-- </div> -->
    
      </section>

   </body>


{% endblock %}


Solution 1:[1]

You can add logic directly inside your view or write a decorator to enforce permissions. For examples, check out the django authentication documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Code-Apprentice