我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.html.format_html()。
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> """)
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 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 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 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 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 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 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), )
def render(self, name, value, attrs=None): label_for = attrs.get('id', '') if not label_for: attrs['id'] = uuid.uuid4() label_for = attrs['id'] return html.format_html( u'<div class="themable-checkbox">{}<label for="{}"></label></div>', super(ThemableCheckboxInput, self).render(name, value, attrs), label_for )
def render(self, name=None, value=None, attrs=None, choices=()): if self.id_for_label: label_for = html.format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else self.attrs return html.format_html( u'<div class="themable-checkbox">{}<label{}>' + u'<span>{}</span></label></div>', self.tag(attrs), label_for, self.choice_label )
def editor_css(): return format_html(""" <link href="{0}{1}" rel="stylesheet" type="text/x-scss" /> """, settings.STATIC_URL, 'vendor/font-awesome/scss/font-awesome.scss')
def link(self, instance): url = reverse('admin:%s_%s_change' % ( RelationshipAssertion._meta.app_label, RelationshipAssertion._meta.model_name), args=(instance.relationshipassertion.id,)) return format_html(u'<a href="{}">{}</a>', url, unicode(instance.relationshipassertion))
def render_js(self): return [ format_html( '<script type="text/javascript" src="{}"></script>', self.absolute_path(path) ) for path in self._js ]
def render_css(self): # To keep rendering order consistent, we can't just iterate over items(). # We need to sort the keys, and iterate over the sorted list. media = sorted(self._css.keys()) return chain(*[[ format_html( '<link href="{}" type="text/css" media="{}" rel="stylesheet" />', self.absolute_path(path), medium ) for path in self._css[medium] ] for medium in media])
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_text(self._format_value(value)) return format_html('<input{} />', flatatt(final_attrs))
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) id_ = final_attrs.get('id') inputs = [] for i, v in enumerate(value): input_attrs = dict(value=force_text(v), **final_attrs) if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. input_attrs['id'] = '%s_%s' % (id_, i) inputs.append(format_html('<input{} />', flatatt(input_attrs))) return mark_safe('\n'.join(inputs))
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) return format_html('<textarea{}>\r\n{}</textarea>', flatatt(final_attrs), force_text(value))
def render(self, name, value, attrs=None, choices=()): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) output = [format_html('<select{}>', flatatt(final_attrs))] options = self.render_options(choices, [value]) if options: output.append(options) output.append('</select>') return mark_safe('\n'.join(output))
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 = '' return format_html('<option value="{}"{}>{}</option>', option_value, selected_html, force_text(option_label))
def render_options(self, choices, selected_choices): # Normalize to strings. selected_choices = set(force_text(v) for v in selected_choices) output = [] for option_value, option_label in chain(self.choices, choices): if isinstance(option_label, (list, tuple)): output.append(format_html('<optgroup label="{}">', force_text(option_value))) for option in option_label: output.append(self.render_option(selected_choices, *option)) output.append('</optgroup>') else: output.append(self.render_option(selected_choices, option_value, option_label)) return '\n'.join(output)
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, name=name) output = [format_html('<select multiple="multiple"{}>', flatatt(final_attrs))] options = self.render_options(choices, value) if options: output.append(options) output.append('</select>') return mark_safe('\n'.join(output))
def render(self, name=None, value=None, attrs=None, choices=()): if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else self.attrs return format_html( '<label{}>{} {}</label>', label_for, self.tag(attrs), self.choice_label )
def render(self): """ Outputs a <ul> for this set of choice fields. If an id was given to the field, it is applied to the <ul> (each item in the list will get an id of `$id_$i`). """ id_ = self.attrs.get('id') output = [] for i, choice in enumerate(self.choices): choice_value, choice_label = choice if isinstance(choice_label, (tuple, list)): attrs_plus = self.attrs.copy() if id_: attrs_plus['id'] += '_{}'.format(i) sub_ul_renderer = self.__class__( name=self.name, value=self.value, attrs=attrs_plus, choices=choice_label, ) sub_ul_renderer.choice_input_class = self.choice_input_class output.append(format_html(self.inner_html, choice_value=choice_value, sub_widgets=sub_ul_renderer.render())) else: w = self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, i) output.append(format_html(self.inner_html, choice_value=force_text(w), sub_widgets='')) return format_html(self.outer_html, id_attr=format_html(' id="{}"', id_) if id_ else '', content=mark_safe('\n'.join(output)))
def as_ul(self): if not self: return '' return format_html( '<ul class="errorlist">{}</ul>', format_html_join('', '<li>{}{}</li>', ((k, force_text(v)) for k, v in self.items())) )
def as_ul(self): if not self.data: return '' return format_html( '<ul class="{}">{}</ul>', self.error_class, format_html_join('', '<li>{}</li>', ((force_text(e),) for e in self)) )
def label_tag(self, contents=None, attrs=None, label_suffix=None): """ Wraps the given contents in a <label>, if the field has an ID attribute. contents should be 'mark_safe'd to avoid HTML escaping. If contents aren't given, uses the field's HTML-escaped label. If attrs are given, they're used as HTML attributes on the <label> tag. label_suffix allows overriding the form's label_suffix. """ contents = contents or self.label if label_suffix is None: label_suffix = (self.field.label_suffix if self.field.label_suffix is not None else self.form.label_suffix) # Only add the suffix if the label does not end in punctuation. # Translators: If found as last label character, these punctuation # characters will prevent the default label_suffix to be appended to the label if label_suffix and contents and contents[-1] not in _(':?.!'): contents = format_html('{}{}', contents, label_suffix) widget = self.field.widget id_ = widget.attrs.get('id') or self.auto_id if id_: id_for_label = widget.id_for_label(id_) if id_for_label: attrs = dict(attrs or {}, **{'for': id_for_label}) if self.field.required and hasattr(self.form, 'required_css_class'): attrs = attrs or {} if 'class' in attrs: attrs['class'] += ' ' + self.form.required_css_class else: attrs['class'] = self.form.required_css_class attrs = flatatt(attrs) if attrs else '' contents = format_html('<label{}>{}</label>', attrs, contents) else: contents = conditional_escape(contents) return mark_safe(contents)
def body(self): "Returns HTML body tag for loading and unloading Google Maps javascript." return format_html('<body {} {}>', self.onload, self.onunload)
def onload(self): "Returns the `onload` HTML <body> attribute." return format_html('onload="{}.{}_load()"', self.js_module, self.dom_id)