I\'m having trouble with Django templates and CharField models.
So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I cr
This tag keeps spaces and newlines. I copied Django's own tag linebreaksbr and then added a line to replace the spaces with nbsp. It does not replace single spaces so text source is still readable. I wrote this because I couldn't get the spacify tag (other answer) to work with linebreaksbr.
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe, SafeData
from django.utils.text import normalize_newlines
from django.utils.html import escape
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def keep_spacing(value, autoescape=None):
autoescape = autoescape and not isinstance(value, SafeData)
value = normalize_newlines(value)
if autoescape:
value = escape(value)
value = mark_safe(value.replace(' ', ' '))
return mark_safe(value.replace('\n', '
'))