Mitya Grebenshchikov
Mitya Grebenshchikov

Reputation: 171

How to create inclusion_tag Django?

I'm a Django Beginner.

I've read the documentation, but found no interaction with the DB.

I want display on one page multiple data from DB! How to implement it using inclusion_tag with argument(received from html template)?

Please help!

Upvotes: 0

Views: 531

Answers (1)

catavaran
catavaran

Reputation: 45555

Template tag is the regular django code so you can use the ORM as usual:

from myapp.models import Message, Like

@register.inclusion_tag('user_stats.html')
def user_stats(user):
    return {'user': user,
            'messages': Message.objects.filter(user=user).count(),
            'likes': Like.objects.filter(user=user).count()}

And then in the user_stats.html:

User: {{ user.username }} - {{ messages }} message(s), {{ likes }} like(s)

UPDATE: To pass the data to the template tag just add the argument to the call:

{% for user in user_list %}
    <div>
        {% user_stats user %}
    </div>
{% endfor %}

Upvotes: 2

Related Questions