Returning manager in template (Django)

0

How do I return the number of books published in the template?

I have this

# models.py
class PublishedManager(models.Manager):

    def published(self):
        return self.filter(published=True)


class Book(models.Model):
    name = models.CharField('nome', max_length=50)
    authors = models.ManyToManyField('Author', verbose_name='autores')
    published = models.BooleanField('publicado', default=True)
    # add our custom model manager
    objects = PublishedManager()

and

#views.py
class BookList(ListView):
    model = Book
    context_object_name = 'books'
    paginate_by = 10

I tried this

# template.html
<p>Livros publicados: {{ books.published.count }}</p>

But it was not.

    
asked by anonymous 08.06.2016 / 09:48

2 answers

2

Regis,

I do not know a way to do this what you want without creating a new filter, or changing the context of your View.

To create a new filter you can look at the Django documentation , but well summarized you would do so:

First you register your new filter:

@register.filter
def count_published(value):
    return value.filter(published=True).count()

Then you use it in the template:

{% load seu_arquivo_de_template_tags %}
<p>Livros publicados: {{ books | count_published }}</p>

There is another way to do that, as well, by modifying get_context_data of your ListView :

class BookList(ListView):
    model = Book
    context_object_name = 'books'
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(BookList, self).get_context_data(**kwargs)
        context['count_published'] = self.model.objects.filter(published=True).count()
        return context

And then use the context variable you passed in your template:

<p>Livros publicados: {{ count_published }}</p>
    
08.06.2016 / 11:00
0

Do this in view.py

#views.py
class BookList(ListView):

    # ...

    books_published = Book.objects.filter(published=True)

and in the template:

# template.html
<p>Livros publicados: {{ books_published|length }}</p>
    
20.10.2016 / 21:47