如何在django中使用User获取组名

时间:2015-02-06 07:10:05

标签: django django-authentication django-orm

我被困在django的组模块中,任何人都可以告诉我如何解决它。 我的问题是现在我不赞成登录用户的用户名,我想显示组名和该组中的个人资料以及用户名。我的观点是这样的,

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

2 个答案:

答案 0 :(得分:1)

用户的群组列表可用作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>

答案 1 :(得分:0)

views.py

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

循环

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