Django:获取将auth.Group作为外键的配置文件

时间:2015-02-10 04:30:09

标签: django django-templates django-authentication django-users

我有一个模型使用auth.models.Group作为名为Dashboard的外键:

class Dashboard(models.Model):
    d_name = models.CharField(max_length=200)
    d_description = models.CharField(max_length=200)
    d_url = models.CharField(max_length=200)
    d_status = models.CharField(max_length=200)
    owner = models.ForeignKey(Group)

    def __str__(self):return self.d_name

我的views.py是:

def custom_login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('dashboards')        
    return login(request, 'login.html', authentication_form=LoginForm)

def custom_logout(request):
    return logout(request, next_page='/')

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

并且在这里使用此dashboards.html我想使用Group_name显示仪表板,我将通过 group.name 获得:

{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
    <p>Welcome, {{ request.user.get_username }}. <br/>
    {% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}

<ul>
{% for group in groups %}
    <li>
        <strong>{{ group.name }}<strong> -

            {{ dashboards.d_name }}{% if not forloop.last %},{% endif %}

    </li>
{% endfor %}
</ul>



{% endblock %}

这里我已经提到了我的问题的所有支持信息,如果有任何解决方案,请告诉我。

2 个答案:

答案 0 :(得分:0)

要访问Dashboard的{​​{1}}列表,请使用Group查询集:

group.dashboard_set

此查询集名为“backward relationship”。

答案 1 :(得分:0)

views.py

def user(request):
    user= request.user
    groups = request.user.groups.all()
    dashboards = Dashboard.objects.filter(owner=groups)

    context = {
        'user': user,
        'groups': groups,
        'dashboards': dashboards,
    }
    return render_to_response('registration/dashboards.html', context, context_instance=RequestContext(request))

和dashboards.html

{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
    <p>Welcome, {{ request.user.get_username }}. <br/>
    {% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}

<ul>
{% for group in groups %}
    <li>
        <strong>you belongs to::{{ group.name }}</strong> </li>
{% endfor %}
</ul>
<strong>#Dashboards available are::</strong>
{% for Dashboard in dashboards %}
    <ol>
	<li>{{ Dashboard.d_name }}-{{ Dashboard.owner }}-{{Dashboard.d_description}}</li> </ol>
{% endfor %}


{% endblock %}

这很好又整洁,,,,