Home > Back-end >  How to check user for 2 fields from another model with ManyToMany fields
How to check user for 2 fields from another model with ManyToMany fields

Time:02-02

How am i suppose to check request.user for 2 fields in the same time

I want to show different pages in header if user is customer or contractor by another many to many field or if he is contractor and customer in same time show both pages

Im not sure how am i suppose to do that

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 ><a  href="{% url 'contractor_view' %}"><span 
                                       >Contractor</span></a></li>
   {% endif %}
{% endfor %}
{% if request.user.is_staff %}
  <li ><a  href="{% url 'admin:index' %}"><span
                                >Admin</span></a></li>
{% endif %}

CodePudding user response:

You need to check if the user is associated with a CounterParty object that has both fields set to True (In your views):

@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)
  • Related