开发者

Creating a tag cloud from a list in Django?

开发者 https://www.devze.com 2023-02-15 16:06 出处:网络
I am getting a list from an API call. I would like to be able to display a tagcloud based on the words in the开发者_运维技巧 list.

I am getting a list from an API call. I would like to be able to display a tagcloud based on the words in the开发者_运维技巧 list.

I have seen some other possible solutions that generate the HTML in the view function but if I am using templates, how can I bypass this step? Also, solutions like using the django plugin the seem to require the use of models which I feel is not necessary in my case.

Anyway to do this?


There are many ways you could do this. Personally I would manipulate the list of tags into this format in you view:

tags = [
    { 'tag': 'django', 'size': 10 },
    { 'tag': 'python', 'size': 8 },
    { 'tag': 'Australia', 'size': 1 },
    { 'tag': 'coffee', 'size': 6 },
    { 'tag': 'pycon', 'size': 3 },
    { 'tag': 'html', 'size': 9 },
]

In your template:

<div class="tag-cloud">
    {% for t in tags %}
        <a href="/blog/tag/{{ t.tag }}/" class="size-{{ t.size }}">{{ t.tag }}</a> 
    {% endfor %}
</div>

In your CSS:

.tag-cloud a.size-1 { font-size: 1.1em }
.tag-cloud a.size-2 { font-size: 1.2em }
.tag-cloud a.size-3 { font-size: 1.3em }
.tag-cloud a.size-4 { font-size: 1.4em }
.tag-cloud a.size-5 { font-size: 1.5em }
.tag-cloud a.size-6 { font-size: 1.6em }
.tag-cloud a.size-7 { font-size: 1.7em }
.tag-cloud a.size-8 { font-size: 1.8em }
.tag-cloud a.size-9 { font-size: 1.9em }
.tag-cloud a.size-10 { font-size: 2em }


Iterate over the tag list in the template and use the "random" filter over an integer list for the inline font-size style.

http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#random

views.py

...
sizes = [10, 12, 14, 16, 18, 20]
tags = ["one", "two", "three"]
...

index.html

...
{% for tag in tags %}
    <a href="/some/url/with/{{ tag }}/" style="font-size: {{ sizes|random }}px">{{ tag }}</a>
{% endfor %}
...


pip install worldcloud

pip install matplotlib

In views.py:

def cloud(request):   
    object1   =   obj.objects.values_list('title', flat=True)
    words =   list(object1)

    # image configurations
    background_color = "#fff"
    height = 720
    width = 1080

   data = dict()
   for word in words:
      word = word.lower()
      data[word] = data.get(word, 0) + 1

    word_cloud = WordCloud(
    background_color=background_color,
    width=width,
    height=height
    )

word_cloud.generate_from_frequencies(data)
word_cloud.to_file('../cdn/cdn_medias/clouds/image.png')

context = {}
return  render(request,'object/cloud.html',context)

In your template:

<img src="/media/clouds/image.png" class="img-fluid w-50">
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号