django自定义标签使用,Bytes/KB/MB/GB相互转换
目录结构
templatetags
--mytags.py
views.py
后端代码 mytags.py
from django import template
register = template.Library()
#bytes单位转换
@register.simple_tag()
def bytes_convert(num):
if not num:
return ''
elif num < 1024:
return str(num) + ' B'
elif 1024 <= num < 1024*1024:
return str(round(num/1024,2)) + ' KB'
elif 1024*1024 <= num < 1024*1024*1024:
return str(round(num/(1024*1024),2)) + ' MB'
else:
return str(round(num/(1024*1024*1024),2)) + ' GB'
前端代码
{% load mytags %} <--導入自定義標籤-->
<td>{% bytes_convert i.bytes %}</td> <--使用標籤-->
参考文章:https://blog.csdn.net/gamer_gyt/article/details/51029109