how to get group name using User in django

随声附和 提交于 2021-02-20 04:47:28

问题


I am stuck in django's group module can any one tell me how to solve it. my problem is now i'm dispalying the username of the logged-in user, i want to display group-name and the profiles present in that group along with the username.and my views are like this,

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

now what do I need to add in order to achieve my requirement

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 is

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

heres my 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

回答1:


User's group list is available as the user.groups related manager:

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

To display this list in the template you have to loop over it:

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



回答2:


views.py

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

in template for loop

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

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

{% endfor %}

for single print

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


来源:https://stackoverflow.com/questions/28360396/how-to-get-group-name-using-user-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!