Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check user for 2 fields from another model with ManyToMany fields

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 %}

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading