1+ from __future__ import annotations
2+ import re
13from django import forms , template
24
35register = template .Library ()
@@ -49,10 +51,29 @@ def field(context: template.Context, field_name: str, field_type: forms.Field, *
4951 return ""
5052
5153
54+ def _to_tuple_if_needed (value : str ) -> str | tuple [str , str ]:
55+ """
56+ Helper function to convert a string into a tuple if it contains a delimiter.
57+
58+ Args:
59+ value (str): The string to be converted.
60+
61+ Returns:
62+ tuple[str, str]: A tuple containing the two parts of the string if it contains a delimiter,
63+ otherwise returns the original string as a single-element tuple.
64+ """
65+ match = re .match (r"^(.*?)\s*<([^>]+)>\s?$" , value )
66+ if match :
67+ return [match .group (1 ).strip (), match .group (2 ).strip ()]
68+ return value
69+
70+
5271@register .filter
53- def split (value : str , delimiter : str = "|" ) -> list [str ]:
72+ def split (value : str , delimiter : str = "|" ) -> list [str ] | list [ tuple [ str , str ]] :
5473 """
5574 Helper that splits a given string into a list of substrings based on a specified delimiter.
75+ If the substring is of the format "Verbose name <value>" it is turned into a 2-tuple
76+ as used by a form field's choices argument.
5677
5778 Args:
5879 value (str): The string to be split.
@@ -61,4 +82,5 @@ def split(value: str, delimiter: str = "|") -> list[str]:
6182 Returns:
6283 list[str]: A list of substrings obtained by splitting the input string using the delimiter.
6384 """
64- return value .split (delimiter )
85+ split_list = value .split (delimiter )
86+ return [_to_tuple_if_needed (item ) for item in split_list ]
0 commit comments