使用模板显示用户的组名

Display group name of user with a template

对于我网站的工作人员,我正在显示所有注册用户的列表,我想显示他们的组。除了我得到 <QuerySet [<Group: UserGroup>]> 而不是 UserGroup 之外,它正在工作。

尝试使用 group = form.cleaned_data['group_name'] 但我收到此错误:以 10 为底的 int() 无效文字:'Viewers' 在 user.groups.add(组)。

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

是否可以使用与{{instance.groups.all}}不同的东西?

这个<td>{{instance.groups.all}}</td>会给出一个查询集。

如果您希望各个组使用

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