本文整理匯總了Python中django.utils.safestring.SafeText方法的典型用法代碼示例。如果您正苦於以下問題:Python safestring.SafeText方法的具體用法?Python safestring.SafeText怎麽用?Python safestring.SafeText使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.utils.safestring
的用法示例。
在下文中一共展示了safestring.SafeText方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_all_markup_langs
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def test_all_markup_langs(self):
"""
Make sure each markup option returns the same way.
"""
correct = '<p>Paragraph <strong>1</strong> \u2605\U0001F600</p>'
markup_samples = [
('creole', '''Paragraph **1** \u2605\U0001F600'''),
('markdown', '''Paragraph **1** \u2605\U0001F600'''),
('html', '''<p>Paragraph <strong>1</strong> \u2605\U0001F600'''),
('textile', '''Paragraph *1* \u2605\U0001F600'''),
]
for lang, markup in markup_samples:
result = markup_to_html(markup, lang)
self.assertIsInstance(result, SafeText)
self.assertEqual(result.strip(), correct)
result = markup_to_html('Paragraph <1> \u2605\U0001F600', 'plain')
self.assertIsInstance(result, SafeText)
self.assertEqual(result.strip(), '<p>Paragraph <1> \u2605\U0001F600</p>')
示例2: adapt_datetime_with_timezone_support
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def adapt_datetime_with_timezone_support(value, conv):
# Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
if settings.USE_TZ:
if timezone.is_naive(value):
warnings.warn("MySQL received a naive datetime (%s)"
" while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
value = value.astimezone(timezone.utc).replace(tzinfo=None)
return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)
# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects.
示例3: html_safe
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def html_safe(klass):
"""
A decorator that defines the __html__ method. This helps non-Django
templates to detect classes whose __str__ methods return SafeText.
"""
if '__html__' in klass.__dict__:
raise ValueError(
"can't apply @html_safe to %s because it defines "
"__html__()." % klass.__name__
)
if '__str__' not in klass.__dict__:
raise ValueError(
"can't apply @html_safe to %s because it doesn't "
"define __str__()." % klass.__name__
)
klass_str = klass.__str__
klass.__str__ = lambda self: mark_safe(klass_str(self))
klass.__html__ = lambda self: str(self)
return klass
示例4: render
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def render(self, name: str, value, attrs=None, renderer=None):
"""
name='project', value=None, attrs={'id': 'id_project'}
<select name="project" id="id_project">
"""
wig_id = attrs['id']
html = self.build_master_change_script(wig_id)
html += f'<select name="{name}" id="{wig_id}">\n'
html += ' <option value="" selected>---------</option>\n'
proj_set = [(p.pk, p.type.code, p.name, p.type_id) for p in self.choices.queryset.order_by('-pk')]
for id, proj_type, proj_name, proj_type_pk in proj_set:
val_str = f'{proj_name} ({proj_type}, #{id})'
html += f' <option value="{id}" data_type="{proj_type_pk}" >'
html += f'{val_str}</option>\n'
html += '</select>\n'
html_safe = SafeText(html)
return html_safe
示例5: test_custom_render_form_template
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def test_custom_render_form_template(self):
class LinkBlock(blocks.StructBlock):
title = blocks.CharBlock(required=False)
link = blocks.URLBlock(required=False)
class Meta:
form_template = 'tests/block_forms/struct_block_form_template.html'
block = LinkBlock()
html = block.render_form(block.to_python({
'title': "Wagtail site",
'link': 'http://www.wagtail.io',
}), prefix='mylink')
self.assertIn('<div>Hello</div>', html)
self.assertHTMLEqual('<div>Hello</div>', html)
self.assertTrue(isinstance(html, SafeText))
示例6: test_custom_render_form_template_jinja
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def test_custom_render_form_template_jinja(self):
class LinkBlock(blocks.StructBlock):
title = blocks.CharBlock(required=False)
link = blocks.URLBlock(required=False)
class Meta:
form_template = 'tests/jinja2/struct_block_form_template.html'
block = LinkBlock()
html = block.render_form(block.to_python({
'title': "Wagtail site",
'link': 'http://www.wagtail.io',
}), prefix='mylink')
self.assertIn('<div>Hello</div>', html)
self.assertHTMLEqual('<div>Hello</div>', html)
self.assertTrue(isinstance(html, SafeText))
示例7: adapt_datetime_warn_on_aware_datetime
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def adapt_datetime_warn_on_aware_datetime(value, conv):
# Remove this function and rely on the default adapter in Django 2.0.
if settings.USE_TZ and timezone.is_aware(value):
warnings.warn(
"The MySQL database adapter received an aware datetime (%s), "
"probably from cursor.execute(). Update your code to pass a "
"naive datetime in the database connection's time zone (UTC by "
"default).", RemovedInDjango20Warning)
# This doesn't account for the database connection's timezone,
# which isn't known. (That's why this adapter is deprecated.)
value = value.astimezone(timezone.utc).replace(tzinfo=None)
return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)
# MySQLdb returns TIME columns as timedelta -- they are more like timedelta in
# terms of actual behavior as they are signed and include days -- and Django
# expects time, so we still need to override that. We also need to add special
# handling for SafeText and SafeBytes as MySQLdb's type checking is too tight
# to catch those (see Django ticket #6052).
示例8: render_field
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def render_field(field: Field, render_labels: bool = True) -> SafeText:
"""
Renders a form field using a custom template designed specifically for the wiki forms.
As the wiki uses custom form rendering logic, we were unable to make use of Crispy Forms for
it. This means that, in order to customize the form fields, we needed to be able to render
the fields manually. This function handles that logic.
Sometimes we don't want to render the label that goes with a field - the `render_labels`
argument defaults to True, but can be set to False if the label shouldn't be rendered.
The label rendering logic is left up to the template.
Usage: `{% render_field field_obj [render_labels=True/False] %}`
"""
unbound_field = get_unbound_field(field)
if not isinstance(render_labels, bool):
render_labels = True
template_path = TEMPLATES.get(unbound_field.__class__, TEMPLATE_PATH.format("in_place_render"))
is_markitup = isinstance(unbound_field.widget, MarkItUpWidget)
context = {"field": field, "is_markitup": is_markitup, "render_labels": render_labels}
return render(template_path, context)
示例9: adapt_datetime_with_timezone_support
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def adapt_datetime_with_timezone_support(value, conv):
# Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
if settings.USE_TZ:
if timezone.is_naive(value):
warnings.warn("MySQL received a naive datetime (%s)"
" while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
value = value.astimezone(timezone.utc).replace(tzinfo=None)
return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S"), conv)
# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects.
示例10: adapt_datetime_warn_on_aware_datetime
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def adapt_datetime_warn_on_aware_datetime(value, conv):
# Remove this function and rely on the default adapter in Django 2.0.
if settings.USE_TZ and timezone.is_aware(value):
warnings.warn(
"The MySQL database adapter received an aware datetime (%s), "
"probably from cursor.execute(). Update your code to pass a "
"naive datetime in the database connection's time zone (UTC by "
"default).", RemovedInDjango20Warning)
# This doesn't account for the database connection's timezone,
# which isn't known. (That's why this adapter is deprecated.)
value = value.astimezone(timezone.utc).replace(tzinfo=None)
return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)
# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
示例11: test_safe_status
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def test_safe_status(self):
"""
Translating a string requiring no auto-escaping with gettext or pgettext
shouldn't change the "safe" status.
"""
trans_real._active = local()
trans_real._translations = {}
s1 = mark_safe('Password')
s2 = mark_safe('May')
with translation.override('de', deactivate=True):
self.assertIs(type(gettext(s1)), SafeText)
self.assertIs(type(pgettext('month name', s2)), SafeText)
self.assertEqual('aPassword', SafeText('a') + s1)
self.assertEqual('Passworda', s1 + SafeText('a'))
self.assertEqual('Passworda', s1 + mark_safe('a'))
self.assertEqual('aPassword', mark_safe('a') + s1)
self.assertEqual('as', mark_safe('a') + mark_safe('s'))
示例12: intro_html
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def intro_html(self) -> SafeText:
return markup_to_html(self.intro, markuplang=self.markup, math=self.math)
示例13: honour_code_html
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def honour_code_html(self) -> SafeText:
return markup_to_html(self.honour_code_text, markuplang=self.honour_code_markup, math=self.honour_code_math)
示例14: question_html
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def question_html(self) -> SafeText:
"""
Markup for the question itself
"""
helper = self.helper()
return helper.question_html()
示例15: question_preview_html
# 需要導入模塊: from django.utils import safestring [as 別名]
# 或者: from django.utils.safestring import SafeText [as 別名]
def question_preview_html(self) -> SafeText:
"""
Markup for an instructor's preview of the question (e.g. question + MC options)
"""
helper = self.helper()
return helper.question_preview_html()