Search code examples
djangodjango-templatesdjango-authenticationdjango-users

Django: get profiles having auth.Group as foreign key


I have an model which uses auth.models.Group as foreign key called 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

my views.py is:

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

and here using this dashboards.html I want to display the dashboards by using the Group_name which i will get as a result of 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 %}

here I have mentioned all the supporting information for my problem, please let me know if there are any solution.


Solution

  • To access the list of Dashboards for the Group use the group.dashboard_set queryset:

    {% for group in groups %}
        <li>
            <strong>{{ group.name }}</strong> -
            {% for dashboard in group.dashboard_set.all %}
                {{ dashboard.d_name }}{% if not forloop.last %},{% endif %}
            {% endfor %}
        </li>
    {% endfor %}
    

    This queryset is called "backward relationship".