How to display the user groups because they didn't show in django view?

I research this from a couple of days but there is not so much information about the groups in django’s documentation, and really can’t figure out what to change so the groups will be display.

I have CRUD operations for users which can be done only from admin and he can assign users to 6 different groups. It saved in the database and everything works well. The problem I faced now is that the groups are not visualize in my views (in the UI).

model.py

class CustomUserManager(BaseUserManager):

    def create_user(self, email, password, **extra_fields):

        if not email:
            raise ValueError(_('The Email must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):

        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, password, **extra_fields)


class CustomUser(AbstractUser):

username = None
email = models.EmailField(_('email address'), unique=True)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

objects = CustomUserManager()

def __str__(self):
    return self.email

username                        = models.CharField(max_length=30, blank=True, default='')
is_superuser                    = models.BooleanField(default=True)
is_admin                        = models.BooleanField(default=True)
is_employee                     = models.BooleanField(default=True)
is_headofdepartment             = models.BooleanField(default=True)
is_reception                    = models.BooleanField(default=True)
is_patient                      = models.BooleanField(default=True)
is_active                       = models.BooleanField(default=True)
is_staff                        = models.BooleanField(default=True)

forms.py

 class UserForm(ModelForm):
     password = forms.CharField(widget=forms.PasswordInput)
     group = forms.ModelChoiceField(queryset=Group.objects.all())

     class Meta:
         model = CustomUser
         fields = [
             'email',
             'password',
             'group',
         ]

     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         self.fields['group'] = ModelChoiceField(
             queryset=Group.objects.all(),
             empty_label='Избери'
         )

users.html

                  {% for user in users %}
                        <tr>
                            <td>{{ user.email }}</td>
                            <td>{{ user.group }}</td>
                            <td>
                                <a href="{% url 'feedback:useredit' user.id %}" class="btn text-secondary px"-0>
                                    <i class="far fa-edit fa-lg"></i>
                                </a>
                                <form action="{% url 'feedback:userdelete' user.id %}" method="post" class="d-inline">
                                    {% csrf_token %}
                                    <button type="submit" class="btn">
                                        <i class="far fa-trash-alt fa-lg text-danger float-right"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    {% endfor %}

views.py

@login_required
@admin_only
def users(request):
    context = {'users': CustomUser.objects.all()}
    return render(request, 'users.html', context)

First, the attribute in the User model is “groups”, not “group”.

And, since Group is a many-to-many relationship with User, you need to iterate through all the Group objects associated with each user.

I understand this, everything with the groups works how I expected, they just doesn’t show in the template. I can’t find any information and resources about how to achieve this and what I’m doing wrong.

Since groups is a collection of objects, you need to iterate over it. This means that within your user loop, you’ll need to do something like:

<td>{{ user.email }}</td>
<td>
{% for group in user.groups.all %}
{{ group.name }}
{% endfor %}
</td>

(Obviously, you would want to style / arrange this to fit your design.)

1 Like

Wow awesome! I thought it’s more complicated because I didn’t find people use it, but your explanation makes sense. Many thanks!