Skip to content
Advertisement

How to replace a comma with an underscore in Django template filter

Hi I have javascript as follows contains django variables.

<script>

$(document).ready(function() {
    {% for a in all_results %}
            $('#{{a.set|slice:":7"}}_{{ a.item }}_{{ a.kidu|slice:":2" }}').html('<a class="a1" href="{% url 'req_detail_view' a.id %}">{{ a.id }}</a>');
            $('#{{a.set|slice:":7"}}_{{ a.item}}_{{ a.kidu|slice:":2" }}').addClass('{{ a.state__name.split|join:"_" }}');
    {% endfor %}
});
</script>

all results are a query result fro my view:

context['all_results'] = m.values('set', 'kidu', 'id', 'item', 'state__name')

The problem am facing is if the value of item is a comma separated value, then the id is not passing to the template I have. But if the value of item is a one word my code is working perfectly and the id is passing to the template. Any idea guys?

Advertisement

Answer

In file where you have you custom filters and tags, add following function

 from django import template
 register = template.Library()

 @register.filter
 def replace_commas(string):
    return string.replace(',', '_')

For view how to create custom filters, view this documentation of django.

  1. Create a folder ‘templatetags’ in your app directory
  2. Create a file name ‘my_filter.py’ and '__init__.py' in that folder
  3. Copy above code in my_filter.py
  4. In you template, add {% load my_filter %} at the top.
  5. Now you can use your filter like this {{m.item|replace_commas}}

Note, you could make the template tag a little more flexible by making the find/replace an argument. e.g.:

from django import template
register = template.Library()

@register.filter
def find_replace(string, find_replace=",|_"):
    find, replace = find_replace.split("|")
    return string.replace(',', '_')

Then you would be able to use it like so in your template:

{{ m.item|find_replace:",|-" }}

(would replace ,‘s with -‘s

Advertisement