You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Django模板菜单项与视图permission_required权限控制联动?

Align Template Menu Permissions with Django View Rules & Improve Dashboard Separation

Great question! Let's walk through how to get your template permissions perfectly synced with your view's permission_required rule, plus fix that dashboard separation to make it feel polished and professional.

Step 1: Fix Template Permission Checks to Match View Rules

Right now, your {% if perms.user %} check is too broad—it just checks if the user has any permission in the user app, not the specific custom permission you defined. Let's fix that alignment first:

First: Correct the Permission Format in Views & Templates

In your models.py, you defined a custom permission like this:

# models.py example
class Customer(models.Model):
    # ... your model fields ...
    class Meta:
        permissions = [
            ("view_user", "Can_view_user"),  # codename: view_user, human-readable name: Can_view_user
        ]

Django permissions follow the format app_label.codename, so if your app is named user, the full permission string should be user.view_user—not just can_view_user.

Update your view to use the correct full permission string:

# views.py
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import ListView

class UsersListView(PermissionRequiredMixin, ListView):
    permission_required = "user.view_user"  # Use full app.codename here to match your model's permission
    # ... rest of your view logic ...

Now, update your menuitem.html to check for this exact permission—this is the key to linking your template and view rules:

<!-- menuitem.html -->
{% if perms.user.view_user %}
    <li class="menu-item">
        <a href="{% url 'users_list' %}">Users</a>
    </li>
{% endif %}

This will only show the Users menu item if the user has the exact permission your view requires—perfect alignment!

Step 2: Add Custom Role Checks (If Needed)

You mentioned a check_permission_BM_or_AM function in permission.py. To use this alongside the permission check in templates, create a custom template tag to make the function accessible:

  1. Create a templatetags folder in your app (add an __init__.py file inside it to make it a valid Python module).
  2. Create permissions_tags.py inside that folder:
# yourapp/templatetags/permissions_tags.py
from django import template
from yourapp.permission import check_permission_BM_or_AM

register = template.Library()

@register.simple_tag
def is_bm_or_am(user):
    return check_permission_BM_or_AM(user)
  1. Load and use the tag in your template to combine both checks:
<!-- menuitem.html -->
{% load permissions_tags %}

{% if perms.user.view_user and is_bm_or_am user %}
    <li class="menu-item">
        <a href="{% url 'users_list' %}">Users</a>
    </li>
{% endif %}

This matches the combined permission + role logic you might enforce in your views.

Step 3: Improve Client/Admin Dashboard Separation

To make the dashboard separation feel professional, move beyond basic conditional checks and use these structured patterns:

1. Use Template Inheritance for Layouts

Create separate base templates for client and admin dashboards to keep layouts clean:

  • base_client.html: Contains client-specific navigation, styling, and footer
  • base_admin.html: Contains admin-specific navigation, tools, and styling

Then, have your client views inherit from base_client.html and admin views inherit from base_admin.html:

<!-- client_dashboard.html -->
{% extends "base_client.html" %}

{% block content %}
<!-- Client-specific dashboard content here -->
{% endblock %}

2. Group-Based Menu Loading

Organize users into Client and Admin groups in the Django admin, then load the appropriate menu based on the user's group:

<!-- base.html (if you want a single entry point) -->
{% if user.groups.filter(name="Admin").exists %}
    {% include "admin_menu.html" %}
{% else %}
    {% include "client_menu.html" %}
{% endif %}

Each menu file (admin_menu.html, client_menu.html) will contain relevant items with their own permission checks, like the one we set up earlier.

3. Use View Mixins to Enforce Dashboard Access

Create mixins to ensure users can only access the correct dashboard:

# mixins.py
from django.contrib.auth.mixins import AccessMixin
from django.shortcuts import redirect

class AdminOnlyMixin(AccessMixin):
    def dispatch(self, request, *args, **kwargs):
        if not request.user.groups.filter(name="Admin").exists():
            return redirect("client_dashboard")
        return super().dispatch(request, *args, **kwargs)

class ClientOnlyMixin(AccessMixin):
    def dispatch(self, request, *args, **kwargs):
        if not request.user.groups.filter(name="Client").exists():
            return redirect("admin_dashboard")
        return super().dispatch(request, *args, **kwargs)

Then use these mixins in your views to lock down access:

# views.py
class AdminDashboardView(AdminOnlyMixin, TemplateView):
    template_name = "admin_dashboard.html"

class ClientDashboardView(ClientOnlyMixin, TemplateView):
    template_name = "client_dashboard.html"

内容的提问来源于stack exchange,提问作者Dhekra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:53:48