Last update on .

尽量让自己的代码都是Unicode的设置吧,能省心不少。

第一步,在app的目录中,创建templatetags文件夹

第二步,文件夹中添加__init__.py,eval_extras.py两个文件。

第三步,eval_extras.py文件中,加入如下内容:

#coding=utf-8
from django import template
from organization.models import Employee

register = template.Library()

#https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/
#If you leave off the name argument, Django will use the functions name as the filter name.
@register.filter(is_safe=True)
def get_employee_name(e_id):
    ele = Employee.objects.get(id = e_id)
    return ele.name

第四步 template中引入templatetags

{% load eval_extras %}

注:在给Django的app添加templatetags的时候,碰到的错误编码:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 255: invalid start byte

解决:

1. eval_extras.py文件中第一行加入#coding=utf-8

2. base.html中加入:    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

评论

No comments yet.

Please log in by using LinkedIn Weibo to leave a comment.