0

I just want to slice a string on django in two parts, passing a caracter like "|"

Example: 2007-007134|10003L

Part 1: 2007-007134

Part 2: 10003L

I tried somethings but without success

Someone can help me?

HudsonBarroso
  • 455
  • 4
  • 20
  • do you mean like this ? if you have it like: example="2007-007134|10003L" then Part_1= example[:10] and part_2=example[12:] – taha maatof Oct 30 '20 at 17:17
  • The code length is not fixed, I have a code like NE | 02023, in this case, it cannot slice correctly. – HudsonBarroso Oct 30 '20 at 18:01
  • how about a split point , like a dash or a point etc, then slice on it, like this https://stackoverflow.com/questions/46766530/python-split-a-string-by-the-position-of-a-character – taha maatof Oct 30 '20 at 18:29

2 Answers2

1

Create a custom template tag. They are basically python code which you can execute from inside the html templates (when using defult Django templating engine).

You can read more about them here:

https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/ https://www.codementor.io/@hiteshgarg14/creating-custom-template-tags-in-django-application-58wvmqm5f

0

I solved according Maciej Rogosz recommended: Custom Template Tag

First: I created the folder templatetags inside of my app, after that create a empty ini.py and finally created my custom_tag.py:

from django import template
register = template.Library()

@register.filter(name='split1')
def split1(value, key):
  return value.split(key)[1]

@register.filter(name='split2')
def split2(value, key):
  return value.split(key)[0]

In my tamplate I have to load the template tags

{% load custom_tags %} 

And call my custom_tags: split1, split2

{{ instance.mat_code|split1:"|" }}
{{ instance.mat_code|split2:"|" }}

That is it, python + django = Magic

Tks to everyone for your help

Ref1: https://www.w3schools.com/python/ref_string_split.asp

Ref2: https://www.codementor.io/@hiteshgarg14/creating-custom-template-tags-in-django-application-58wvmqm5f

HudsonBarroso
  • 455
  • 4
  • 20