-1

I need to get list of all authors and their publishes

{% for author in authors %}
  {{ author.name }}
  {% for publish in publishes %}
    {{ publish.title }}
  {% endfor %}
{% endfor %}

views.py:

def authors_list(request):
    authors = Author.objects.all()
    publishes = Group.objects.filter(author=author)
    return render(request, 'app/authors_list.html', {'authors': authors,'publishes': publishes})

This way 'publishes' is not Defined.

  • 1
    Well, indeed you have not defined it before you use it. But this is not the right approach; you should be following the relationship between each author and its "publishes" in the template itself. – Daniel Roseman Jun 01 '17 at 15:36
  • @DanielRoseman is right I just underlined the error – Szabolcs Dombi Jun 01 '17 at 15:39

2 Answers2

0

The problem is that publishes is not defined while you are trying to define publishes

It is misleading but the error is marked below:

publishes = Group.objects.filter(publishes=publishes)
                                           ^^^^^^^^^

I hope it will help you find the problem.

After your edit:

publishes = Group.objects.filter(author=author)
                                        ^^^^^^

I think you will need to define a @propery for Author:

Read this

Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71
  • yeah, i know. The documentaion says that this way it call the pk. If use publishes__author it calls the only one authors. publishes__author='Admin' . Is there a way to use all authors and all their publishes? – M. Trevino Jun 01 '17 at 15:40
0

Assuming you have a ForeignKey in Group model, You could do something like this,

{% for author in authors %}    
    {{ author.name }}
    {% for publish in author.group_set.all() %}
        {{ publish.title }}
    {% endfor %}
{% endfor %}

You could access the groups of your authors with the related name.

For that, you can also define a related_name for your convenience. You could add,

author = models.ForeignKey(Author, related_name='groups')

in your Group model.

If you have added the related_name, then you can call the related_objects like,

{% for publish in author.groups.all() %}

in your template.

Then change your views,

def authors_list(request):
    authors = Author.objects.all()
    return render(request, 'app/authors_list.html', {'authors': authors})
zaidfazil
  • 9,017
  • 2
  • 24
  • 47