[Django]-Django-taggit create tagcloud from queryset

4👍

django-taggit-templatetags appears to be the ‘go-to’ place for a tagcloud for django-taggit.

It doesn’t appear to handle querysets though. 🙁

So, I’ve added:

@register.inclusion_tag('taggit_templatetags/tagcloud_include_qs.html')
def include_tagcloud_qs(queryset):
    try:
        queryset = queryset.annotate(num_times=Count('taggeditem_items'))
    except FieldError:
        queryset = queryset.annotate(num_times=Count('taggit_taggeditem_items'))

    num_times = queryset.values_list('num_times', flat=True)

    weight_fun = get_weight_fun(T_MIN, T_MAX, min(num_times), max(num_times))
    queryset = queryset.order_by('name')
    for tag in queryset:
        tag.weight = weight_fun(tag.num_times)

    return {"tags": queryset}

to

templatetags/taggit_extras.py

And this to a new file at taggit_templatetags/tagcloud_include_qs.html

<div>
{% for tag in tags %}
<font size={{tag.weight|floatformat:0}}>{{tag}}</font> 
{% endfor %}
</div>

I’m using it like this in my templates:

{% include_tagcloud_qs my_queryset %}

I haven’t spent much time looking at the django-taggit-templatetags code, so feel free to update this with a better solution!

PS:

I’m getting a queryset in my view like this:

my_queryset = Tag.objects.filter(foo__bar=baz).distinct()

2👍

This answer shows how to build a tag cloud. You’d create a queryset in your view according to your parameters, generate a dictionary, and render it in your templates as shown in that answer.

0👍

I would suggest using django-tagging. It is well documented. I have created tag clouds with it. You can access tag clouds via model, model instance, etc via template tags that are easy to load. This is a little hackish but using the .counts method you can hack up some css to increase the size of each font as you would see in a real tag cloud. Django-tagging actually excels in this area as it has a default template tag with formatting options for everything you have described.

👤eusid

0👍

I’ve added a TagBase.get_for() function in https://github.com/twig/django-taggit/commit/42cd4e04f00496103f295c0afd8297074be50dcf

This basically fetches the Tags used for a given queryset, and from there you can do what you need to do.

👤twig

Leave a comment