Example of how to split a string in a Django template
Introduction
Let's consider the following example: with a table in models.py file with a row called tags (which is a string: models.TextField() ):
class Note(models.Model):... = ...... = ...... = ...tags = models.TextField()
and tags is used to store labels separated by a semicolon ; (i.e. for example: New_York; Travel; Photo).
The goal is to split the string tags in a django template.
Create a filter
Django application directories should look like:
/my_app//templates//static/models.pyviews.py
under my_app (replace my_app by the name of your application), create a folder named templatetags:
mkdir templatetags/my_app//templates//static/models.pyviews.py/templatetags/
Under templatetags create a empty file called
__init__.py
and a file called filter.py
from django import templateregister = template.Library()@register.filter(name='split')def split(value, key):"""Returns the value turned into a list."""return value.split(key)
Update settings.py
Add the following lines in the settings.py file (replace my_app):
'libraries':{# make your file entry here.'filter_tags': 'my_app.templatetags.filter',}
Should look like this:
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [],'APP_DIRS': True,'OPTIONS': {'context_processors': ['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],'libraries':{# make your file entry here.'filter_tags': 'my_app.templatetags.filter',}},},]
Pass table note to the template
from .models import Notedef images_view(request):.........note_obj = Note.objects.all()context = {'note_obj':note_obj}return render(request, "my_app/template.html", context )
Create a list in the template
In template.html add the following line at the top:
{% load filter_tags %}
now the filter can be used to split the string note_obj,tags
{% with note_obj.tags|split:";" as tags %}{% for tag in tags %}{{tag}}{% endfor %}{% endwith %}
References
| Links | Site |
|---|---|
| Django How can i split string using template tag | stackoverflow |
| Custom template tags and filters | stackoverflow |
| how to split the string in django template? | stackoverflow |
