Django custom template tag filter 추가

2021. 1. 16. 18:02파이썬/Django

1. 앱/templatetags 디렉토리 생성

2. /templatetags/filter.py 파일 생성 

- 앱이 다른 경우, 파일명을 다르게 해야 함(동일하면 에러 발생)

- 첫번째 앱의 파일만 인식함

- django를 재기동해야 적용됨

from django import template
register = template.Library()

@register.filter(name='lower')
def lower(value):
	return value.lower()​
from django import template
register = template.Library()

def lower(value):
	return value.lower()
    
register.filter('lower', lower)
from django import template
register = template.Library()

@register.filter
def lower(value):
	return value.lower()

파라메터 적용하기

from django import template

register = template.Library()

@register.filter
def decode(value,arg) :
    return value.decode(arg)

날짜정보를 밀리세컨드로 변경하기

import datetime
from django import template
#from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
#@stringfilter
def convert_miliseconds(value) :
    return int(datetime.datetime(value.year,value.month,value.day).timestamp() * 1000)

3. template에 적용하기

{% extends 'admin/change_form.html' %}
{% load filters2 %}
{% block after_related_objects %}
<img src='data:image/png;base64,{{original.image_data|decode:'utf-8'}}'/>

{% endblock%}

Custom template tags and filters | Django documentation | Django (djangoproject.com)

 

Custom template tags and filters | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

Built-in template tags and filters | Django 문서 | Django (djangoproject.com)

 

 

Built-in template tags and filters | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com