python 如何从另一个具有多对多字段的模型中检查2个字段的用户

ejk8hzay  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(130)

我应该如何检查request.user的2个字段在同一时间
如果用户是客户或承包商,我希望在页眉中显示不同的页面(通过另一个多对多字段),或者如果用户是承包商和客户,同时显示两个页面
我不知道我该怎么做
Models.py:

class CounterParty(models.Model):
    GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True)
    name = models.CharField(max_length=150, verbose_name='Name')
    customer = models.BooleanField(default=False, verbose_name='customer')
    contractor = models.BooleanField(default=False, verbose_name='contractor')
    counter_user = models.ManyToManyField(User, blank=True, related_name='counter_user')

views.py:

@login_required
def home_view(request):

    counter_party = CounterParty.objects.all()

    context = {
        'counter_party': counter_party
    }

    return render(request, 'common/home.html', context)

header.html:

{% for counter in counter_party %}
   {% if request.user in counter.counter_user.all %}
      <li class="nav-item"><a class="nav-link" href="{% url 'contractor_view' %}"><span 
                                       class="nav-link-title">Contractor</span></a></li>
   {% endif %}
{% endfor %}
{% 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 %}
7eumitmz

7eumitmz1#

您需要检查用户是否与两个字段都设置为TrueCounterParty对象相关联(在您的视图中):

@login_required
def home_view(request):
    counter_party = CounterParty.objects.filter(counter_user=request.user)
    customer = False
    contractor = False
    for cp in counter_party:
        if cp.customer:
            customer = True
        if cp.contractor:
            contractor = True
    context = {
        'customer': customer,
        'contractor': contractor,
    }
    return render(request, 'common/home.html', context)

相关问题