def editor_js():
js_files = [
'javascripts/hallo.js',
]
js_includes = format_html_join('\n', '<script src="{0}{1}"></script>',
((settings.STATIC_URL, filename)
for filename in js_files)
)
return js_includes + format_html("""
<script>
registerHalloPlugin('blockQuoteButton');
registerHalloPlugin('editHtmlButton');
</script>
""")
python类format_html()的实例源码
def render(self, name, value, attrs):
encoded = value
final_attrs = self.build_attrs(attrs)
if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX):
summary = mark_safe("<strong>%s</strong>" % ugettext("No password set."))
else:
try:
hasher = identify_hasher(encoded)
except ValueError:
summary = mark_safe("<strong>%s</strong>" % ugettext(
"Invalid password format or unknown hashing algorithm."))
else:
summary = format_html_join('',
"<strong>{}</strong>: {} ",
((ugettext(key), value)
for key, value in hasher.safe_summary(encoded).items())
)
return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
def render(self, context):
csrf_token = context.get('csrf_token')
if csrf_token:
if csrf_token == 'NOTPROVIDED':
return format_html("")
else:
return format_html("<input type='hidden' name='csrfmiddlewaretoken' value='{}' />", csrf_token)
else:
# It's very probable that the token is missing because of
# misconfiguration, so we raise a warning
if settings.DEBUG:
warnings.warn(
"A {% csrf_token %} was used in a template, but the context "
"did not provide the value. This is usually caused by not "
"using RequestContext."
)
return ''
def render(self, name, value, attrs):
encoded = value
final_attrs = self.build_attrs(attrs)
if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX):
summary = mark_safe("<strong>%s</strong>" % ugettext("No password set."))
else:
try:
hasher = identify_hasher(encoded)
except ValueError:
summary = mark_safe("<strong>%s</strong>" % ugettext(
"Invalid password format or unknown hashing algorithm."
))
else:
summary = format_html_join(
'', '<strong>{}</strong>: {} ',
((ugettext(key), value) for key, value in hasher.safe_summary(encoded).items())
)
return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
def label_for_value(self, value):
key = self.rel.get_related_field().name
try:
obj = self.rel.model._default_manager.using(self.db).get(**{key: value})
except (ValueError, self.rel.model.DoesNotExist):
return ''
label = ' <strong>{}</strong>'
text = Truncator(obj).words(14, truncate='...')
try:
change_url = reverse(
'%s:%s_%s_change' % (
self.admin_site.name,
obj._meta.app_label,
obj._meta.object_name.lower(),
),
args=(obj.pk,)
)
except NoReverseMatch:
pass # Admin not registered for target model.
else:
text = format_html('<a href="{}">{}</a>', change_url, text)
return format_html(label, text)
def display_for_field(value, field, empty_value_display):
from django.contrib.admin.templatetags.admin_list import _boolean_icon
if getattr(field, 'flatchoices', None):
return dict(field.flatchoices).get(value, empty_value_display)
# NullBooleanField needs special-case null-handling, so it comes
# before the general null test.
elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
return _boolean_icon(value)
elif value is None:
return empty_value_display
elif isinstance(field, models.DateTimeField):
return formats.localize(timezone.template_localtime(value))
elif isinstance(field, (models.DateField, models.TimeField)):
return formats.localize(value)
elif isinstance(field, models.DecimalField):
return formats.number_format(value, field.decimal_places)
elif isinstance(field, (models.IntegerField, models.FloatField)):
return formats.number_format(value)
elif isinstance(field, models.FileField) and value:
return format_html('<a href="{}">{}</a>', value.url, value)
else:
return display_for_value(value, empty_value_display)
def get_editor_js_for_registration(cls):
js_files = cls.get_editor_js_files()
js_includes = format_html_join(
'\n', '<script src="{0}{1}"></script>',
((settings.STATIC_URL, filename) for filename in js_files)
)
return js_includes + format_html(
"""
<script>
window.chooserUrls.{0}Chooser = '{1}';
</script>
""",
cls.model._meta.object_name,
urlresolvers.reverse('{}_chooser'.format(cls.model._meta.model_name))
)
def build_attrs(self, attrs={}, **kwargs):
to_opts = self.rel.to._meta
if "class" not in attrs:
attrs['class'] = 'select-search'
else:
attrs['class'] = attrs['class'] + ' select-search'
attrs['data-search-url'] = self.admin_view.get_admin_url(
'%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
attrs['data-choices'] = '?'
if self.rel.limit_choices_to:
for i in list(self.rel.limit_choices_to):
attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
attrs['data-choices'] = format_html(attrs['data-choices'])
return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
def display_for_field(value, field, empty_value_display):
from django.contrib.admin.templatetags.admin_list import _boolean_icon
if getattr(field, 'flatchoices', None):
return dict(field.flatchoices).get(value, empty_value_display)
# NullBooleanField needs special-case null-handling, so it comes
# before the general null test.
elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
return _boolean_icon(value)
elif value is None:
return empty_value_display
elif isinstance(field, models.DateTimeField):
return formats.localize(timezone.template_localtime(value))
elif isinstance(field, (models.DateField, models.TimeField)):
return formats.localize(value)
elif isinstance(field, models.DecimalField):
return formats.number_format(value, field.decimal_places)
elif isinstance(field, (models.IntegerField, models.FloatField)):
return formats.number_format(value)
elif isinstance(field, models.FileField) and value:
return format_html('<a href="{}">{}</a>', value.url, value)
else:
return display_for_value(value, empty_value_display)
def build_attrs(self, attrs={}, extra_attrs=None, **kwargs):
to_opts = self.rel.to._meta
if "class" not in attrs:
attrs['class'] = 'select-search'
else:
attrs['class'] = attrs['class'] + ' select-search'
attrs['data-search-url'] = self.admin_view.get_admin_url(
'%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
attrs['data-choices'] = '?'
if self.rel.limit_choices_to:
for i in list(self.rel.limit_choices_to):
attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
attrs['data-choices'] = format_html(attrs['data-choices'])
if DJANGO_11:
attrs.update(kwargs)
return super(ForeignKeySearchWidget, self).build_attrs(attrs, extra_attrs=extra_attrs)
else:
if extra_attrs:
attrs.update(extra_attrs)
return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
def build_attrs(self, attrs={}, **kwargs):
to_opts = self.rel.to._meta
if "class" not in attrs:
attrs['class'] = 'select-search'
else:
attrs['class'] = attrs['class'] + ' select-search'
attrs['data-search-url'] = self.admin_view.get_admin_url(
'%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
attrs['data-choices'] = '?'
if self.rel.limit_choices_to:
for i in list(self.rel.limit_choices_to):
attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
attrs['data-choices'] = format_html(attrs['data-choices'])
return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
def login(request):
username = auth.get_user(request).username
if (username):
return redirect('/')
else:
args = {}
args.update(csrf(request))
if request.POST:
username = request.POST.get('username','')
password = request.POST.get('password','')
user = auth.authenticate(username=username, password=password)
if user is not None:
if not request.POST.get('remember-me', ''):
request.session.set_expiry(0)
auth.login(request, user)
return redirect('/')
else:
args['login_error'] = format_html("<div class=\"main-error alert alert-error\">???????????? ??? ???????????? ??? ??????</div>")
return render_to_response('login.html', args)
else:
return render_to_response('login.html', args)
def register(request):
username = auth.get_user(request).username
if not (username):
args={}
args.update(csrf(request))
args['form']=UserCreationForm()
if request.POST:
newuser_form=UserCreationForm(request.POST)
if newuser_form.is_valid():
newuser_form.save()
newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],password=newuser_form.cleaned_data['password2'])
auth.login(request, newuser)
return redirect('/')
else:
args['errors'] = format_html('<div class="main-error alert alert-error">?????? ??? ???????????</div>')
args['form'] = newuser_form
return render_to_response('register.html',args)
else:
return redirect('/')
def indented_title(self, instance):
"""
Use Unicode box-drawing characters to visualize the tree hierarchy.
"""
box_drawing = []
for i in range(instance.depth - 2):
box_drawing.append('<i class="l"></i>')
if instance.depth > 1:
box_drawing.append('<i class="a"></i>')
return format_html(
'<div class="box">'
'<div class="box-drawing">{}</div>'
'<div class="box-text" style="text-indent:{}px">{}</div>'
'</div>',
mark_safe(''.join(box_drawing)),
(instance.depth - 1) * 30,
instance,
)
def build_attrs(self, attrs={}, **kwargs):
to_opts = self.rel.to._meta
if "class" not in attrs:
attrs['class'] = 'select-search'
else:
attrs['class'] = attrs['class'] + ' select-search'
attrs['data-search-url'] = self.admin_view.get_admin_url(
'%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
attrs['data-choices'] = '?'
if self.rel.limit_choices_to:
for i in list(self.rel.limit_choices_to):
attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
attrs['data-choices'] = format_html(attrs['data-choices'])
return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
def async_css(href):
"""
Outputs a link and noscript tag, which will asynchronously load an external stylesheet.
Sample usage::
<head>
...
{% async_css '/static/foo.css' %}
...
</head>
Results in::
<head>
...
<link rel="preload" href="/static/foo.css" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/static/foo.css"></noscript>
...
</head>
"""
return format_html(''.join([
'<link rel="preload" href="{0}" as="style" onload="this.rel=\'stylesheet\'">',
'<noscript><link rel="stylesheet" href="{0}"></noscript>'
]), href)
def async_css(href):
"""
Outputs a link and noscript tag, which will asynchronously load an external stylesheet.
Sample usage::
<head>
...
{% async_css '/static/foo.css' %}
...
</head>
Results in::
<head>
...
<link rel="preload" href="/static/foo.css" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/static/foo.css"></noscript>
...
</head>
"""
return format_html(''.join([
'<link rel="preload" href="{0}" as="style" onload="this.rel=\'stylesheet\'">',
'<noscript><link rel="stylesheet" href="{0}"></noscript>'
]), href)
def build_attrs(self, attrs={}, **kwargs):
to_opts = self.rel.to._meta
if "class" not in attrs:
attrs['class'] = 'select-search'
else:
attrs['class'] = attrs['class'] + ' select-search'
attrs['data-search-url'] = self.admin_view.get_admin_url(
'%s_%s_changelist' % (to_opts.app_label, to_opts.model_name))
attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name
attrs['data-choices'] = '?'
if self.rel.limit_choices_to:
for i in list(self.rel.limit_choices_to):
attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i])
attrs['data-choices'] = format_html(attrs['data-choices'])
return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
def domain_urlize(value):
"""
Returns an HTML link to the supplied URL, but only using the domain as the
text.
e.g. if `my_url` is 'http://www.example.org/foo/' then:
{{ my_url|domain_urlize }}
returns:
<a href="http://www.example.org/foo/" rel="nofollow">www.example.org</a>
"""
parsed_uri = urlparse(value)
domain = '{uri.netloc}'.format(uri=parsed_uri)
return format_html('<a href="{}" rel="nofollow">{}</a>',
value,
domain
)
def render_option(self, selected_choices, option_value, option_label):
if option_value is None:
option_value = ''
option_value = force_text(option_value)
if option_value in selected_choices:
selected_html = mark_safe(' selected="selected"')
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
data_circuit_attr = ''
if option_value:
from driver27.models import GrandPrix
grand_prix = GrandPrix.objects.filter(pk=option_value)
if grand_prix.count() and grand_prix.first().default_circuit:
data_circuit_attr = getattr(grand_prix.first().default_circuit, 'pk', '')
return format_html('<option value="{}"{} data-circuit="{}">{}</option>',
option_value, selected_html,
data_circuit_attr, force_text(option_label))
def render(self, name, value, attrs=None):
if value is None:
return format_html(
'<p class="text-error">{text}</p>',
text=_('Populate form fields above'),
)
final_attrs = self.build_attrs(attrs)
href = smart_urlquote(value)
text = self.text or href
return format_html(
'<p><a href="{href}" {attrs}>{text}</a></p>',
href=href,
attrs=flatatt(final_attrs),
text=force_str(text),
)
def render_label(content, label_for=None, label_class=None, label_title='', optional=False):
"""
Render a label with content
"""
attrs = {}
if label_for:
attrs['for'] = label_for
if label_class:
attrs['class'] = label_class
if label_title:
attrs['title'] = label_title
builder = '<{tag}{attrs}>{content}{opt}</{tag}>'
return format_html(
builder,
tag='label',
attrs=mark_safe(flatatt(attrs)) if attrs else '',
opt=mark_safe('<br><span class="optional">{}</span>'.format(pgettext('form', 'Optional'))) if optional else '',
content=text_value(content),
)
def render(self, name, value, attrs):
encoded = value
final_attrs = self.build_attrs(attrs)
if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX):
summary = mark_safe("<strong>%s</strong>" % ugettext("No password set."))
else:
try:
hasher = identify_hasher(encoded)
except ValueError:
summary = mark_safe("<strong>%s</strong>" % ugettext(
"Invalid password format or unknown hashing algorithm."
))
else:
summary = format_html_join(
'', '<strong>{}</strong>: {} ',
((ugettext(key), value) for key, value in hasher.safe_summary(encoded).items())
)
return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
def label_for_value(self, value):
key = self.rel.get_related_field().name
try:
obj = self.rel.model._default_manager.using(self.db).get(**{key: value})
except (ValueError, self.rel.model.DoesNotExist):
return ''
label = ' <strong>{}</strong>'
text = Truncator(obj).words(14, truncate='...')
try:
change_url = reverse(
'%s:%s_%s_change' % (
self.admin_site.name,
obj._meta.app_label,
obj._meta.object_name.lower(),
),
args=(obj.pk,)
)
except NoReverseMatch:
pass # Admin not registered for target model.
else:
text = format_html('<a href="{}">{}</a>', change_url, text)
return format_html(label, text)
def display_for_field(value, field, empty_value_display):
from django.contrib.admin.templatetags.admin_list import _boolean_icon
if getattr(field, 'flatchoices', None):
return dict(field.flatchoices).get(value, empty_value_display)
# NullBooleanField needs special-case null-handling, so it comes
# before the general null test.
elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
return _boolean_icon(value)
elif value is None:
return empty_value_display
elif isinstance(field, models.DateTimeField):
return formats.localize(timezone.template_localtime(value))
elif isinstance(field, (models.DateField, models.TimeField)):
return formats.localize(value)
elif isinstance(field, models.DecimalField):
return formats.number_format(value, field.decimal_places)
elif isinstance(field, (models.IntegerField, models.FloatField)):
return formats.number_format(value)
elif isinstance(field, models.FileField) and value:
return format_html('<a href="{}">{}</a>', value.url, value)
else:
return display_for_value(value, empty_value_display)
def editor_css():
return format_html(
'<link rel="stylesheet" href="%(static_url)sdemo/css/'
'admin-streamfield-styles.css">' % {'static_url': settings.STATIC_URL}
)
def image_tag(url):
return format_html(
"<img src='{root}{url}' />".format(
root=settings.MEDIA_URL or '',
url=url,
)
)
def format_acme_url(self, acme_object):
"""Format the ACME url from the ACME challenge object"""
object_url = acme_object.get_acme_url()
if object_url:
return format_html(
"<a href='{}'>ACME Challenge Link</a>",
object_url,
)
return '-'
def format_acme_url(self, acme_object):
"""Format the ACME url from the ACME challenge object"""
object_url = acme_object.get_acme_url()
if object_url:
return format_html(
"<a href='{}'>ACME Challenge Link</a>",
object_url,
)
return '-'
def render_tag(tag, attrs=None, content=None, close=True):
"""
Render a HTML tag
"""
builder = '<{tag}{attrs}>{content}'
if content or close:
builder += '</{tag}>'
return format_html(
builder,
tag=tag,
attrs=mark_safe(flatatt(attrs)) if attrs else '',
content=text_value(content),
)