Search code examples
djangodjango-viewsdjango-usersusergroups

Display group name of user with a template


For the staff members of my website, I am displaying a list of all users registered and I want to display their group. It's working except that I get <QuerySet [<Group: UserGroup>]> instead of UserGroup.

Tried to use group = form.cleaned_data['group_name'] but I get this error: invalid literal for int() with base 10: 'Viewers' at user.groups.add(group).

forms.py:

class RegisterForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False)
    last_name = forms.CharField(max_length=30, required=False)
    Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ]
    group_name = forms.ChoiceField(choices=Group)
    is_active = forms.BooleanField(initial=True, required=False)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', 'is_active', )

views.py:

@login_required
@group_required('Staff')
def registerView(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            group = Group.objects.get(name=request.POST.get('group_name'))
            user.groups.add(group)
            return redirect('accounts:users')
    else:
        form = RegisterForm()

    return render(request, 'accounts/register.html', {'form': form})


# Display all active users in a table
class UserView(LoginRequiredMixin, GroupRequiredMixin, ListView):
        template_name = 'accounts/display_users.html'
        group_required = ['Staff']
        queryset = User.objects.filter(is_active=True)

display_users.html:

{% block main %}
<table class="table">
  <thead class="thead-dark">
    <p>
    <tr>
      <th scope="col"># id</th>
      <th scope="col">Username</th>
      <th scope="col">Group</th>
      <th scope="col">Email address</th>
      <th scope="col">First name</th>
      <th scope="col">Last name</th>
    </tr>
  </thead>
{%for instance in object_list%}
     <tbody>
    <tr>
      <td>{{instance.id}}</td>
      <td><a href = "{% url 'accounts:update' instance.id %}">{{instance}}</a></td>
      <td>{{instance.groups.all}}</td>
      <td>{{instance.email}} </td>
      <td>{{instance.first_name}} </td>
      <td>{{instance.last_name}} </td>
    </tr>
  </tbody>
    {% endfor %}
</table>
{% endblock %}

Is there a possibility to use something different of {{instance.groups.all}}?


Solution

  • This <td>{{instance.groups.all}}</td> will give a queryset.

    If you want the individual groups use

     <td>{% for group in instance.groups.all %}{{group}}{% if not forloop.last %},{% endif %}{% endfor %}</td>