How to configure custom filter in django framework?

 # -*- coding: utf-8 -*-
from django import template
register = template.Library()

@register.inclusion_tag('menu/create_minimenu.html', takes_context = True)
def minimenu(context):
....
....
@register.inclusion_tag('menu/create_topmenu.html', takes_context = True)
def topmenu(context):
....
....
@register.filter(name = 'commatodot')
def commatodot(value, arg):
    return str(value).replace(",", '.')
commatodot.isSafe = True

template.html

...
initGeolocation2({{ place.longitude|commatodot }}, {{ place.latitude|commatodot }}, "MAIN");
...

Error:

TemplateSyntaxError at /places/3/

Invalid filter: 'commatodot'

Request Method:     GET
Request URL:    http://localhost:8000/places/3/
Django Version:     1.2.4
Exception Type:     TemplateSyntaxError
Exception Value:    

Invalid filter: 'commatodot'

These tags from the file work well, but there is no filter. But I do not know why...

+3
source share
2 answers

1. Have you placed the filter file inside the module templatetagsin your application? Ie, you should have a structure like:

project/
  my_app/
    templatetags/
      __init__.py    # Important! It makes templatetags a module. You can put your filters here, or in another file.
      apptags.py     # Or just put them in __init__.py

2. Have you included tags? You need something like

{% load apptags %}

in your template.

+24
source

To create a custom filter in django, follow these steps:

1). Create the template_tags folder in your application.

2). Add / copy the file __init__.pyin this folder to make sure it is a python folder.

3). your_custom_filter_name.py:

from django import template register = template.Library()

@register.filter(name = 'get_class') '''A filter for get class name of object.''' def get_class(value): return value.__class__.__name__

4). , {% load your_custom_filter_name%} html.
.

5). :)

https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/

+9

Source: https://habr.com/ru/post/1790813/


All Articles