如何在 Django 中使用用户获取组名

how to get group name using User in django

我被困在 django 的组模块中,谁能告诉我如何解决它。 我的问题是现在我正在显示登录用户的用户名,我想显示组名和该组中的配置文件以及 username.and 我的观点是这样的,

def user(request):
    context = {'user': request.user}
    return render_to_response('username.html', context,
                              context_instance=RequestContext(request))

现在我需要添加什么才能达到我的要求

forms.py

class LoginForm(forms.Form):
        username = forms.CharField(label=(u'User Name'))
        password = forms.CharField(label=(u'Password'),
                                widget=forms.PasswordInput(render_value=False))

username.html 是

{% if user.is_authenticated %}
    <p>Welcome, {{ request.user.get_username }}. <br/>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}

这是我的 model.py

class userprofile(models.Model):
    u_name = models.CharField(max_length=200)
    u_description = models.CharField(max_length=200)
    u_url = models.CharField(max_length=200)
    u_status = models.CharField(max_length=200)
    owner = models.ForeignKey(Group)

    def __str__(self):return self.u_name

用户的组列表可作为 user.groups 相关管理员使用:

def user(request):
    context = {'user': request.user,
               'groups': request.user.groups.all()}
    return render_to_response('username.html', context,
                              context_instance=RequestContext(request))

要在模板中显示此列表,您必须对其进行循环:

<ul>
{% for group in groups %}
    <li>
        <strong>{{ group.name }}<strong> -
        {% for profile in group.userprofile_set.all %}
            {{ profile.u_name }}{% if not forloop.last %},{% endif %}
        {% endfor %}
    </li>
{% endfor %}
</ul>

views.py

class StuffListView(LoginRequiredMixin, ListView):
model = User
template_name = 'users/stuff_list.html'
context_object_name = 'stuffs'

在模板中 for循环

{% for stuff in stuffs %}
     <tr>
        <td>{{ stuff.username }}</td>

        <td>{{stuff.groups.all.0.name}}</td>
     </tr>

{% endfor %}

单张打印

<a>{{stuff.groups.all.0.name}}</a>