Python django.forms.utils 模块,flatatt() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.utils.flatatt()。
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, 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 pagephoto_tag(instance, nocache=False):
attrs = flatatt({
'src': instance.photo.normal.url_nocache if nocache else instance.photo.normal.url,
'srcset': ', '.join((
instance.photo.wide.srcset_nocache,
instance.photo.normal.srcset_nocache,
instance.photo.mobile.srcset_nocache
)),
'width': instance.photo.wide.width,
'height': instance.photo.wide.height,
'sizes': '100vw',
'data-id': instance.id,
'data-source': instance.photo.url_nocache,
'data-crop': instance.photo.croparea,
})
return """<img alt="" {attrs}>""".format(
attrs=attrs,
)
def simplephoto_tag(instance, nocache=False):
attrs = flatatt({
'src': instance.photo.url_nocache if nocache else instance.photo.url,
'srcset': ', '.join((
instance.photo.srcset_nocache,
instance.photo.mobile.srcset_nocache
)),
'width': instance.photo.width,
'height': instance.photo.height,
'sizes': '100vw',
})
return """<img data-id="{id}" alt="" {attrs}>""".format(
id=instance.id,
attrs=attrs,
)
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(self, name, value, attrs=None):
if value is None:
value = ''
text_value = force_text(value)
final_attrs = self.build_attrs(attrs, name=name)
if text_value != '':
final_attrs['value'] = text_value
choices = tuple(self.choices)
choices_dict = dict(choices)
return render_to_string(self.template, {
'widget': self,
'attrs': flatatt(final_attrs),
'value': text_value,
'choices': choices,
'initial_position': choices_dict.get(text_value, (0, 0)),
})
def render(self, name, value, attrs=None):
short_name = self.get_short_name(name)
self._cache_data((self.app_label, self.model_name, short_name))
# ?????????
final_attrs = self.build_attrs(attrs, name=name, **{
'data-url': self.get_url(short_name),
'data-min_chars': self.min_chars,
'data-expressions': self.expressions,
'data-filters': ','.join(item[1] for item in self.filters),
})
# ????????? ?????
classes = final_attrs.get('class', '')
final_attrs['class'] = classes + ' autocomplete_widget'
# ?????????????? ?????????????? ????????
if isinstance(value, (list, tuple)):
value = ','.join(force_text(item) for item in value)
return render_to_string(self.template, {
'attrs': flatatt(final_attrs),
'value': value or '',
'name': name,
})
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
# ????????? ?????? ? ???????????? ???????
classes = final_attrs.pop('class', '')
context = dict(self.context, **{
'name': name,
'value': value,
'classes': classes,
'attrs': flatatt(final_attrs),
'preview': getattr(value, self.context['preview_variation']['name'], None),
})
return mark_safe(render_to_string(self.get_template(), context))
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 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, name, value, attrs=None):
if value is None:
value = ""
if VERSION < (1, 11):
final_attrs = self.build_attrs(attrs, name=name)
else:
final_attrs = self.build_attrs(attrs, {'name': name})
if "class" not in final_attrs:
final_attrs["class"] = ""
final_attrs["class"] += " wmd-input"
template = loader.get_template(self.template)
# Compatibility fix:
# see https://github.com/timmyomahony/django-pagedown/issues/42
context = {
"attrs": flatatt(final_attrs),
"body": conditional_escape(force_unicode(value)),
"id": final_attrs["id"],
"show_preview": self.show_preview,
}
context = Context(context) if VERSION < (1, 9) else context
return template.render(context)
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, 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, 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, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name, size=2)
final_attrs['type'] = 'hidden'
if value != '':
final_attrs['value'] = force_text(self._format_value(value))
self.js_attrs['class'] = ' '.join([
'intl-tel-input', final_attrs.get('class', '')
]).strip()
output = [format_html('<input{}>', flatatt(final_attrs))]
select = self.render_select()
output.append(select)
return mark_safe('\n'.join(output))
def render(self, name, value, attrs=None):
if value is None:
value = ''
extra_attrs = dict()
extra_attrs['type'] = self.input_type
extra_attrs['name'] = name
input_attrs = self.build_attrs(attrs, extra_attrs)
if value != '':
# Only add the 'value' attribute if a value is non-empty.
input_attrs['value'] = force_text(self._format_value(value))
input_attrs = {key: conditional_escape(val) for key, val in input_attrs.items()}
if not self.picker_id:
self.picker_id = (input_attrs.get('id', '') + '_pickers').replace(' ', '_')
self.div_attrs['id'] = self.picker_id
picker_id = conditional_escape(self.picker_id)
div_attrs = {key: conditional_escape(val) for key, val in self.div_attrs.items()}
icon_attrs = {key: conditional_escape(val) for key, val in self.icon_attrs.items()}
html = self.html_template % dict(div_attrs=flatatt(div_attrs),
input_attrs=flatatt(input_attrs),
icon_attrs=flatatt(icon_attrs))
if self.options:
js = self.js_template % dict(picker_id=picker_id, options=json_dumps(self.options or {}))
else:
js = ''
return mark_safe(force_text(html + js))
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 video_tag(self, attrs=None):
if attrs is None:
attrs = {}
else:
attrs = attrs.copy()
if self.thumbnail:
attrs['poster'] = self.thumbnail.url
transcodes = self.transcodes.exclude(processing=True).filter(error_message__exact='')
sources = []
for transcode in transcodes:
sources.append("<source src='{0}' type='video/{1}' >".format(transcode.url, transcode.media_format.name))
mime = mimetypes.MimeTypes()
sources.append("<source src='{0}' type='{1}'>"
.format(self.url, mime.guess_type(self.url)[0]))
sources.append("<p>Sorry, your browser doesn't support playback for this video</p>")
return mark_safe(
"<video {0}>\n{1}\n</video>".format(flatatt(attrs), "\n".join(sources)))
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, 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, 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, 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, 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, name, value, attrs=None):
if value is None:
value = ""
if VERSION < (1, 11):
final_attrs = self.build_attrs(attrs, name=name)
else:
final_attrs = self.build_attrs(attrs, {'name': name})
final_attrs = self.build_attrs(final_attrs, self.attrs)
if "class" not in final_attrs:
final_attrs["class"] = ""
final_attrs["class"] += " wmd-input"
template = loader.get_template(self.template)
# Compatibility fix:
# see https://github.com/timmyomahony/django-pagedown/issues/42
context = {
"attrs": flatatt(final_attrs),
"body": conditional_escape(force_unicode(value)),
"id": final_attrs["id"],
"show_preview": self.show_preview,
}
context = Context(context) if VERSION < (1, 9) else context
return template.render(context)
def render(self, name, value, attrs=None, choices=()):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
output = [
"""<div%(attrs)s>"""
""" <button class="btn btn-group-label%(disabled)s" type="button">%(label)s</button>"""
""" <button class="btn btn-default dropdown-toggle%(disabled)s" type="button" data-toggle="dropdown">"""
""" <span class="caret"></span>"""
""" </button>"""
""" <ul class="dropdown-menu">"""
""" %(options)s"""
""" </ul>"""
""" <input type="hidden" name="%(name)s" value="" class="btn-group-value" />"""
"""</div>"""
"""<noscript>%(noscript)s</noscript>""" %
{'attrs': flatatt(final_attrs),
'options': self.render_options(choices, [value]),
'label': _('Select an option'),
'name': name, 'disabled': ' disabled' if self.disabled else '',
'noscript': self.noscript_widget.render(name, value, {})}]
return mark_safe('\n'.join(output))
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):
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):
final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
if self.check_test(value):
final_attrs['checked'] = 'checked'
if not (value is True or value is False or value is None or value == ''):
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_text(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, 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 tag(self, attrs=None):
attrs = attrs or self.attrs
final_attrs = dict(attrs, type=self.input_type, name=self.name, value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
return format_html('<input{} />', flatatt(final_attrs))
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 render(self):
"""Outputs a <ul> for this set of radio fields."""
return format_html('<ul{}>\n{}\n</ul>',
flatatt(self.attrs),
format_html_join('\n', '<li>{}</li>',
((force_text(w),) for w in self)))
def render(self, name, value, attrs=None):
html = super(AdminURLFieldWidget, self).render(name, value, attrs)
if value:
value = force_text(self._format_value(value))
final_attrs = {'href': smart_urlquote(value)}
html = format_html(
'<p class="url">{} <a{}>{}</a><br />{} {}</p>',
_('Currently:'), flatatt(final_attrs), value,
_('Change:'), html
)
return html
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):
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):
final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
if self.check_test(value):
final_attrs['checked'] = 'checked'
if not (value is True or value is False or value is None or value == ''):
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_text(value)
return format_html('<input{} />', flatatt(final_attrs))
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
output = [format_html('<select{}>', flatatt(final_attrs))]
options = self.render_options([value])
if options:
output.append(options)
output.append('</select>')
return mark_safe('\n'.join(output))
def tag(self, attrs=None):
attrs = attrs or self.attrs
final_attrs = dict(attrs, type=self.input_type, name=self.name, value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
return format_html('<input{} />', flatatt(final_attrs))
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 render(self):
"""Outputs a <ul> for this set of radio fields."""
return format_html('<ul{}>\n{}\n</ul>',
flatatt(self.attrs),
format_html_join('\n', '<li>{}</li>',
((force_text(w),) for w in self)))
def render(self, name, value, attrs=None):
html = super(AdminURLFieldWidget, self).render(name, value, attrs)
if value:
value = force_text(self.format_value(value))
final_attrs = {'href': smart_urlquote(value)}
html = format_html(
'<p class="url">{} <a{}>{}</a><br />{} {}</p>',
_('Currently:'), flatatt(final_attrs), value,
_('Change:'), html
)
return html
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
final_attrs['class'] = 'nav nav-pills nav-stacked'
output = [u'<ul%s>' % flatatt(final_attrs)]
options = self.render_options(force_text(value), final_attrs['id'])
if options:
output.append(options)
output.append(u'</ul>')
output.append('<input type="hidden" id="%s_input" name="%s" value="%s"/>' %
(final_attrs['id'], name, force_text(value)))
return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None):
final_attrs = self.build_attrs(attrs, name=name)
output = [format_html('<select{0}>', flatatt(final_attrs))]
if value:
output.append(format_html('<option selected="selected" value="{0}">{1}</option>', value, self.label_for_value(value)))
output.append('</select>')
return mark_safe('\n'.join(output))
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 render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
final_attrs['class'] = 'nav nav-pills nav-stacked'
output = [u'<ul%s>' % flatatt(final_attrs)]
options = self.render_options(force_text(value), final_attrs['id'])
if options:
output.append(options)
output.append(u'</ul>')
output.append('<input type="hidden" id="%s_input" name="%s" value="%s"/>' %
(final_attrs['id'], name, force_text(value)))
return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None):
if DJANGO_11:
final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})
else:
final_attrs = self.build_attrs(attrs, name=name)
output = [format_html('<select{0}>', flatatt(final_attrs))]
if value:
output.append(format_html('<option selected="selected" value="{0}">{1}</option>', value, self.label_for_value(value)))
output.append('</select>')
return mark_safe('\n'.join(output))