Why use is_safe?

I am reading Django documentation on a custom filter.

and .. I see no reason for the existence of is_safe. https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping

when I encoded some examples and then tried them, the result was always the same if is_safe is True or False.

Why are you using is_safe?

Here is my code

extra_tags.py

from django.template.defaultfilters import stringfilter from django import template import datetime register = template.Library() @register.filter(name='custom_lower') @stringfilter def lower(value): is_safe = True return '%sxx'%value lower.is_safe = True; from django.utils.html import conditional_escape from django.utils.safestring import mark_safe @register.filter(name='custom_lf') def initial_letter_filter(text, autoescape=None): first, other = text[0], text[1:] if autoescape: esc = conditional_escape else: esc = lambda x: x result = '<strong>%s</strong>%s' % (esc(first), esc(other)) return mark_safe(result) initial_letter_filter.is_safe = False initial_letter_filter.needs_autoescape = True 

I want to say that if I code is_safe = True or is_safe = False, the result will be automatically spared by characters .. and I don’t understand why we use is_safe.

+4
source share
1 answer

Using is_safe with mark_safe() is redundant, so you probably don't see the difference.

As noted in the section you are attached to down where it talks about mark_safe() :

In this case, there is no need to worry about the is_safe attribute (although including it will not hurt anything). Whenever you manually handle auto-escaping problems and return a safe string, the is_safe attribute will not change anything anyway.

is_safe is just a way to automatically mark the return value of a function as safe, given that all external inputs were already safe. Django will still autoescape everything that was input, but it will not try to avoid the other parts that were subsequently added by your function.

mark_safe() , on the other hand, confirms that the output is safe regardless of whether the inputs were safe - this is a much stronger requirement that you need to fulfill if you intend to use it.

+11
source

All Articles