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

如何通过多对多字段校验用户双角色并展示对应页面

实现按用户角色动态显示导航的方案

第一步:优化视图,精准获取用户关联的角色数据

直接修改views.py,不要查询所有CounterParty,只获取当前用户绑定的记录,同时提前计算好用户的角色状态,减少模板中的冗余逻辑:

@login_required
def home_view(request):
    # 获取当前用户关联的所有CounterParty对象
    user_counters = request.user.counter_user.all()
    
    # 提前判断用户是否拥有客户/承包商身份
    has_customer_role = user_counters.filter(customer=True).exists()
    has_contractor_role = user_counters.filter(contractor=True).exists()

    context = {
        'has_customer_role': has_customer_role,
        'has_contractor_role': has_contractor_role,
        # 若模板需要用到具体的CounterParty对象,保留此字段
        'user_counters': user_counters
    }
    return render(request, 'common/home.html', context)

第二步:修改模板,按角色渲染对应导航项

更新header.html,利用视图传入的角色状态直接判断显示,避免无效循环,逻辑更清晰:

<!-- 显示客户导航项 -->
{% if has_customer_role %}
<li class="nav-item">
    <a class="nav-link" href="{% url 'customer_view' %}">
        <span class="nav-link-title">客户中心</span>
    </a>
</li>
{% endif %}

<!-- 显示承包商导航项 -->
{% if has_contractor_role %}
<li class="nav-item">
    <a class="nav-link" href="{% url 'contractor_view' %}">
        <span class="nav-link-title">承包商中心</span>
    </a>
</li>
{% endif %}

<!-- 管理员导航项保留原有逻辑 -->
{% if request.user.is_staff %}
<li class="nav-item">
    <a class="nav-link" href="{% url 'admin:index' %}">
        <span class="nav-link-title">Admin</span>
    </a>
</li>
{% endif %}

补充说明

  • 若用户绑定了多个CounterParty,只要其中任意一个的customer字段为True,就会显示客户导航;承包商身份判断逻辑同理。
  • 如果需要严格绑定到某个特定CounterParty的角色,可以在模板中循环user_counters逐个判断,但提前在视图中处理角色状态的方式性能更优。
  • 请确保customer_view和contractor_view已在urls.py中配置对应的路由。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:45:20