Returning manager in template (Django)

Asked

Viewed 45 times

0

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

I have it

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

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

But it wasn’t.

2 answers

2


Regis,

i don’t know a way to do this 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 of doing also that would be the modification of get_context_data of his 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 in your template the context variable you passed:

<p>Livros publicados: {{ count_published }}</p>

0

Do this on 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.