思路来源:https://blog.csdn.net/qq_25046261/article/details/79577933
此功能目的,将在数据库存储的/root/pycharm_project_365/static/train_set/20152670/030_3.bmp在前端转换成/static/train_set/20152670/030_3.bmp。由于从后端传入前端的数据是大批量的,因此无法直接在后端转换后传入前端(或者说实现过于繁琐)因此借助于自定义的filter来实现此功能。
首先先建立文件夹以及文件:
在自己的app底下建立templatetags(名字是什么whatever),底下建立保存filter的.py文件(名字是什么whatever)
在setting中配置文件:
filters.py文件:
from django import template
register = template.Library()
@register.filter(name='get_img_path') # name为使用filter时候的名字
def img_location(img_full_path):
img_split = img_full_path.split("/")
print("img_split", img_split)
img_src = ""
for i in range(len(img_split)):
if i <= 2:
continue
else:
img_src = img_src + "/" + img_split[i]
print("img_src", img_src)
img_name = "/" + img_src.split("/")[-4] + "/" + img_src.split("/")[-3] + "/" + img_src.split("/")[-2] + "/" + \
img_src.split("/")[-1]
print("img_name", img_name)
return img_name
输出的结果:
前端页面:
{% extends 'base_teacher.html' %}
{% block content %}
<h1 class="page-header">查看学生<a href="/create_course/" class="pull-right">《返回上层</a></h1>
<table class="table table-striped">
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>电话</th>
<th>邮箱</th>
<th>图片</th>
</tr>
</thead>
<tbody>
{% load filters %}
{% for i in results %}
<tr>
<td>{{ i.stu.studentNum }}</td>
<td>{{ i.stu.username }}</td>
<td>{{ i.stu.phone }}</td>
<td>{{ i.stu.email }}</td>
<td>
<img src="{{ i.stu.img1|get_img_path }}" alt="学生人脸-{{ i.stu.studentNum }}-{{ i.stu.username }}"
height="100">
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
实现结果: