用模板显示用户的组名

时间:2019-08-01 10:11:18

标签: django django-views django-users usergroups

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

试图使用group = form.cleaned_data ['group_name'],但出现此错误:int()的字面值无效,以10为基数: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 %}

是否可以使用{{instance.groups.all}}以外的其他方式?

1 个答案:

答案 0 :(得分:1)

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

如果您希望各个组使用

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