Search code examples
pythondjangodjango-template-filters

How can I filter groups based on user_id in django-template-language


how can I filter the groups based on the user in Django-template-language with if else condition

 <tbody>
      {% for group in groups %}
      <tr>
          <td>{{group.name}}</td>                                       
          <td><input type="checkbox" name="add_group[]" id="group-{{group.id}}" value=" 
          {{group.id}}" 
                                   
           checked   
           ></td>
                                                                       
       </tr>
     {% endfor %}                                 
  </tbody>

enter image description here


Solution

  • You can access an User group with related object reference or in DTL with a dot notation: User.groups.all.

    For instance, if you want checked only in groups that a specific user is in:

    urls.py:

    urlpatterns = [
        ...
        path('user/<int:id>/', views.user_detail, name='user-detail')
        ...
    ]
    

    views.py

    from django.shortcuts import get_object_or_404
    from django.contrib.auth.models import Group
    
    def user_detail(request, id):
        user = get_object_or_404(User, id=id)
        groups = Group.objects.all()
        context = {
            'user': user,
            'groups': groups
        }
        return render(request, 'user_group.html', context)
    

    user_group.html

    {% extends 'base.html' %}
    
    {% block content %}
    <h1>Username: {{user.username}}</h1>
    
    <h2>Groups</h2>
    <tbody>
        {% for group in groups %}
        <tr>
            <td>{{group.name}}</td>                                   
            <td>
                <input 
                    type="checkbox" 
                    name="add_group[]" 
                    id="group-{{group.id}}" 
                    value="{{group.id}}" 
                    {% if group in user.groups.all %} checked {% endif %}
                >
            </td>                                                        
         </tr>
       {% endfor %}                                 
    </tbody>
    {% endblock %}