在Django中从列表创建标签云?
我从一个API获取了一个列表。我想根据这个列表中的词语显示一个标签云。
我看到了一些其他的解决方案,它们是在视图函数中生成HTML代码,但如果我使用模板的话,怎么才能跳过这一步呢?还有像使用django插件这样的解决方案,似乎需要用到模型,但我觉得在我的情况下这并不是必要的。
有没有办法做到这一点呢?
3 个回答
0
pip install worldcloud
pip install matplotlib
在 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)
在你的模板里:
<img src="/media/clouds/image.png" class="img-fluid w-50">
0
在模板中遍历标签列表,并对一个整数列表使用“随机”过滤器来设置内联字体大小样式。
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 %}
...
8
有很多方法可以做到这一点。个人来说,我会在你的视图中把标签列表处理成这个格式:
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 },
]
在你的模板中:
<div class="tag-cloud">
{% for t in tags %}
<a href="/blog/tag/{{ t.tag }}/" class="size-{{ t.size }}">{{ t.tag }}</a>
{% endfor %}
</div>
在你的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 }