对于我网站的工作人员,我正在显示所有注册的用户的列表,我想显示他们的组。它正在工作,除了我获得<QuerySet [<Group: UserGroup>]>
而不是用户组。
尝试使用group = form.cleaned_data ['group_name'],但我会得到此错误:insus.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}}}}}的东西?
此<td>{{instance.groups.all}}</td>
将给出一个QuerySet。
如果您要单个组使用
<td>{% for group in instance.groups.all %}{{group}}{% if not forloop.last %},{% endif %}{% endfor %}</td>