def render(self, name, value, attrs={}, choices=()): if 'readonly' in attrs and attrs['readonly'] != False: if value: value_text = self.get_labels([value])[0]['text'] final_attrs = self.build_attrs(attrs, name=name, value=value, type="hidden") output = [format_html('<input{}>', flatatt(final_attrs))] value = self.get_labels([value])[0]['text'] del final_attrs['id'] del final_attrs['type'] final_attrs['value'] = value_text final_attrs['disabled'] = 'disabled' output.append(format_html('<input{}>', flatatt(final_attrs))) return mark_safe('\n'.join(output)) else: final_attrs = self.build_attrs(attrs, name=name) output = [format_html('<input{}>', flatatt(final_attrs))] return mark_safe('\n'.join(output)) if self.ajax: attrs.update({ 'data-ajax--url': attrs.get('data-ajax--url', self.reverse()) }) final_attrs = self.build_attrs(attrs, name=name) output = [format_html('<select{}>', flatatt(final_attrs))] if not self.ajax or value is not None: options = self.render_options(choices, value if isinstance(value, list) else [value]) if options: output.append(options) output.append('</select>') return mark_safe('\n'.join(output))
def render(self, name, value, attrs=None, choices=()): nodes = self.get_nodes(value) if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name, value=value, type='hidden') display_attrs = { 'id': "display_{0}".format(name), 'class': 'form-control', 'value': self.display } output = """ <input {attrs} /> <div id="down_{name}" class="input-group"> <input {display_attrs}> <div class="input-group-addon"><i class="glyphicon glyphicon-chevron-down"></i></div> </div> <div id="zTree_{name}" class="zTreeBackground left" style="display:none"> <ul id="tree_{name}" class="ztree"></ul> </div> {script} """ script = loader.render_to_string('public/object_tree.html', {'nodes': mark_safe(json.dumps(nodes)), 'name': name}) return format_html(output, attrs=flatatt(final_attrs), display_attrs=flatatt(display_attrs), name=force_text(name), script=mark_safe(script))
def format_output(self, rendered_widgets, attrs=None): final_attrs = {'class': self.classname} id_ = attrs.get('id') if id_: final_attrs['id'] = id_ rendered = [] hidden = [] for i, subwidget in enumerate(self.named_widgets.items()): widget_name, widget = subwidget if widget.is_hidden: hidden.append(rendered_widgets[i]) else: label = self._labels.get(widget_name, '') if label: label_attrs = {} title = self._help_texts.get(widget_name) if title: label_attrs['title'] = title label = format_html('<label {}>{}</label>', flatatt(label_attrs), label) rendered.append(format_html('<li>{}{}</li>', label, rendered_widgets[i])) return format_html('<ul {}>{}{}</ul>', flatatt(final_attrs), mark_safe(''.join(hidden)), mark_safe(''.join(rendered)) )
def render(self, name, value, attrs=None): if value is None: value = '' input_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. input_attrs['value'] = force_text(self._format_value(value)) input_attrs = dict([(key, conditional_escape(val)) for key, val in input_attrs.items()]) # python2.6 compatible 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 = dict( [(key, conditional_escape(val)) for key, val in self.div_attrs.items()]) # python2.6 compatible icon_attrs = dict([(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: self.options['language'] = translation.get_language() 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=None, choices=()): cts = ContentType.objects.all() tree = [dict(id=self.app_base+index, pId=0, name=force_str(app), checked='false', open='true') for index, app in enumerate(SYSTEM_APPS)] for index, ct in enumerate(cts): if ct.app_label in SYSTEM_APPS: model_id = self.model_base + index tree.append(dict(id=model_id, pId=SYSTEM_APPS.index(ct.app_label)+self.app_base, name=force_str(ct.model), checked='false')) model_permissions = ct.permission_set.all() for mp in model_permissions: tree.append(dict(id=mp.id, pId=model_id, name=force_str(mp.name), checked='false')) final_attrs = self.build_attrs(attrs, name=name, value=value, type='hidden') display_attrs = { 'id': "display_{0}".format(name), 'class': 'form-control', 'value': self.display } output = """ <input {attrs} /> <div id="down_{name}" class="input-group" style="display:none"> <input {display_attrs}> <div class="input-group-addon"><i class="glyphicon glyphicon-chevron-down"></i></div> </div> <div id="zTree_{name}" class="zTreeBackground left"> <ul id="tree_{name}" class="ztree"></ul> </div> {script} """ script = loader.render_to_string('group_tree.html', {'nodes': mark_safe(json.dumps(tree)), 'name': name, 'toggle': 'false'}) return format_html(output, attrs=flatatt(final_attrs), display_attrs=flatatt(display_attrs), name=force_text(name), script=mark_safe(script))
def render(self, name, value, attrs=None): if value is None: value = '' attrs = dict(attrs) attrs.update(name=name) attrs.update(value=value) attrs.update(type=self.input_type) input_attrs = self.build_attrs(self.attrs, 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 = dict([(key, conditional_escape(val)) for key, val in input_attrs.items()]) div_attrs = dict([(key, conditional_escape(val)) for key, val in self.div_attrs.items()]) icon_attrs = dict([(key, conditional_escape(val)) for key, val in self.icon_attrs.items()]) button_attrs = dict([(key, conditional_escape(val)) for key, val in self.button_attrs.items()]) html = self.html_template % dict(div_attrs=flatatt(div_attrs), input_attrs=flatatt(input_attrs), button_attrs=flatatt(button_attrs), icon_attrs=flatatt(icon_attrs)) return mark_safe(force_text(html))
def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs) final_attrs['name'] = name assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'" mce_config = self.profile.copy() #mce_config.update(get_language_config(self.content_language)) #if tinymce.settings.USE_FILEBROWSER: #mce_config['file_browser_callback'] = "djangoFileBrowser" mce_config.update(self.mce_attrs) mce_config['selector'] = '#%s' % final_attrs['id'] # Fix for js functions #js_functions = {} #for k in ('paste_preprocess','paste_postprocess'): #if k in mce_config: #js_functions[k] = mce_config[k] #del mce_config[k] mce_json = json.dumps(mce_config) #for k in js_functions: #index = mce_json.rfind('}') #mce_json = mce_json[:index]+', '+k+':'+js_functions[k].strip()+mce_json[index:] if mce_config.get('inline', False): html = [u'<div%s>%s</div>' % (flatatt(final_attrs), escape(value))] else: html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))] html.append(u'<script type="text/javascript">tinyMCE.init(%s)</script>' % mce_json) return mark_safe(u'\n'.join(html))
def render(self, name, value, attrs=None): if value is None: value = "" input_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != "": # Only add the 'value' attribute if a value is non-empty. input_attrs["value"] = force_text(self._format_value(value)) input_attrs = dict([(key, conditional_escape(val)) for key, val in input_attrs.items()]) # python2.6 compatible 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 = dict( [(key, conditional_escape(val)) for key, val in self.div_attrs.items()] ) # python2.6 compatible icon_attrs = dict([(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 != False: lang = translation.get_language() self.options["locale"] = lang_map.get(lang, lang) 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=None): widget_attrs = self.build_widget_attrs(name) autocomplete = self.autocomplete(values=value) attrs = self.build_attrs(attrs, autocomplete=autocomplete) self.html_id = attrs.pop('id', name) choices = autocomplete.choices_for_values() values = [autocomplete.choice_value(c) for c in choices] context = { 'name': name, 'values': values, 'choices': choices, 'widget': self, 'attrs': safestring.mark_safe(flatatt(attrs)), 'widget_attrs': safestring.mark_safe(flatatt(widget_attrs)), 'autocomplete': autocomplete, } context.update(self.extra_context) template = getattr(autocomplete, 'widget_template', self.widget_template) return safestring.mark_safe(render_to_string(template, context))
def render(self, name, value, attrs=None, renderer=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 admin_thumb(self, obj): try: image = getattr(obj, self.thumb_image_field_name, None) except AttributeError: raise ImproperlyConfigured( u"The `thumb_image_field_name` attribute on your `%s` class " "must name a field on your model." % self.__class__.__name__ ) img_attrs = { 'src': self.thumb_default, 'width': self.thumb_image_width, 'class': self.thumb_classname, } if not image: if self.thumb_default: return mark_safe('<img{}>'.format(flatatt(img_attrs))) return '' # try to get a rendition of the image to use from wagtail.wagtailimages.shortcuts import get_rendition_or_not_found spec = self.thumb_image_filter_spec rendition = get_rendition_or_not_found(image, spec) img_attrs.update({'src': rendition.url}) return mark_safe('<img{}>'.format(flatatt(img_attrs)))
def render(self, name, value, attrs=None): options = self.gather_options() display_text = self.get_display_text(value) return format_html( PERSISTENT_AUTOCOMPLETE_TEMPLATE, flatatt({"data-options": json.dumps(options)}), flatatt({"value": display_text, "name": name}))
def test_flatatt(self): ########### # flatatt # ########### self.assertEqual(flatatt({'id': "header"}), ' id="header"') self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"') self.assertEqual(flatatt({}), '')
def render(self, name, value, attrs=None, renderer=None): app_label = self.model._meta.app_label model_name = self.model._meta.model_name info = (self.site.name, app_label, model_name) if self.queryset_id is not None: search_url = reverse_lazy("yaaac:search_with_queryset_id", kwargs={"app": app_label, "model": model_name, "queryset_id": self.queryset_id}) else: search_url = reverse_lazy("yaaac:search", kwargs={"app": app_label, "model": model_name}) # Cannot just do self.opts.pop("search_fields") because render() must be side-effect free. search_fields = self.opts.get("search_fields") search_opts = self.opts.copy() del search_opts["search_fields"] # https://code.djangoproject.com/ticket/24252#ticket lookup_url = reverse_lazy('%s:%s_%s_changelist' % info, current_app=self.site.name) params = self.url_parameters() url_params = '?' + '&'.join('%s=%s' % (k, v) for k, v in params.items()) attrs.update({ 'class': 'yaaac_%s yaaac_pk vForeignKeyRawIdAdminField' % clean_fieldname_prefix(name), 'search_url': u"{search_url}{url_params}&suggest_by={suggest_by}".format(search_url=str(search_url), url_params=url_params, suggest_by=self.opts["suggest_by"]), 'search_opts': json.dumps(search_opts), 'search_fields': ",".join(search_fields), }) hidden_input = super(AutocompleteWidget, self).render(name, value, attrs) autocomp_input_attrs = { "type": "text", "class": "yaaac_search_input", "placeholder": "start typing to search", "style": value and "display:none" or "" } # flatatt in Django < 1.11 does not handle None values. if not value and "required" in attrs: autocomp_input_attrs["required"] = "" autocomp_input = format_html('<input{0} />', flatatt(autocomp_input_attrs)) lookup_elem = '' if self.opts['allow_lookup'] is True: lookup_elem = format_html('<a {0}><img {1} /></a>', flatatt({"href": u"{lookup_url}{url_params}".format(lookup_url=lookup_url, url_params=url_params), "id": "lookup_id_%s" % name, "class": "yaaac_lookup", "style": value and "display:none" or ""}), flatatt({"width": "16", "height": "16", "alt": "Lookup", "src": static('django_yaaac/img/selector-search.gif')})) return format_html(u'<span class="yaaac_container{}">{}{}{}{}</span>', ' {}'.format(self.attrs['class']) if 'class' in self.attrs else '', hidden_input, autocomp_input, lookup_elem, self.value_elem(value))
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type='hidden', name=name) final_attrs['value'] = force_text(value) if final_attrs['value'] is '': return format_html('<input{} />\n{}\n', flatatt(final_attrs), format_html(self.html)) else: return format_html('<input{} />\n{}\n<br><img id="id_img" src="{}"/>', flatatt(final_attrs), format_html(self.html), final_attrs['value']+"!preview")
def render(self, name, value, attrs=None): attrs.update( {'default-country': 'us', 'preferred-countries': 'us ca', 'name': name} ) final_attrs = self.build_attrs(self.attrs, attrs) # Use a hack to init ng-model ng_model_init = {'ng-model': final_attrs['ng-model'], 'value': value} return format_html( '<input type="hidden" {}/>' + '<bc-phone-number {}></bc-phone-number>', flatatt(ng_model_init), flatatt(final_attrs), )
def render(self,name,values,attrs=None): #attrs = {} label_for = format_html('<label for="id_city">城市:</label>') select_province = format_html('<select {}><option>------</option></select>',flatatt({'id':'province','name':'province'})) select_city = format_html('<select {}></select>',flatatt({'id':'city','name':'city'})) html = ''.join((label_for,select_province,select_city)) # html.append() #html[1] = format_html('<select {}>---</select>',flatatt(self.city_attrs)) #output = [] #for field in self._parse_date_fmt(): # output.append(html[field]) return html
def render(self, name, value=None, attrs=None, prelabel=None): self.attrs.update(attrs or {}) final_attrs = self.build_attrs(self.attrs, name=name) prelabel = prelabel or self.prelabel if prelabel: out = u'<label for="%s" >%s</label><input type="checkbox"%s >' \ % (self.attrs.get("id", ""), value or self.label, flatatt(final_attrs)) else: out = u'<input type="checkbox"%s ><label for="%s" >%s</label>' \ % (flatatt(final_attrs), self.attrs.get("id", ""), value or self.label) return mark_safe(out)
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)) input_html = format_html('<input{} />', flatatt(final_attrs)) error_div_attrs = { 'id': 'form_error_%s' % final_attrs['id'] } error_div = '<div><span class="error-container label label-danger"{}></span></div>' error_div_html = format_html(error_div, flatatt(error_div_attrs)) return '%s%s' % (input_html, error_div_html)
def render(self, name, value, attrs=None, renderer=None): if self.allow_multiple_selected: error_msg = '{0}.render() does not support multi-selection.' raise NotImplementedError(error_msg.format(self.__class__.__name__)) if value is None: value = '' final_attrs = self.build_attrs(base_attrs=attrs, extra_attrs={'name': name}) final_attrs['class'] = final_attrs.get('class', '').replace('form-control', '') final_attrs['class'] += ' btn-group button-select-widget' input_attrs = { 'id': final_attrs.pop('id'), 'name': final_attrs.pop('name'), 'value': value, } options = self.render_options([value]) js = ''' <script> function buttonClick(evt) { evt.preventDefault(); var btn = this; var btnContainer = btn.parentNode; btnContainer.querySelector('input[type="hidden"]').value = btn.value; [].forEach.call(btnContainer.querySelectorAll('.btn'), function (elem) { elem.className = elem.className.replace(/active/, ''); }); btn.className += 'active'; } [].forEach.call(document.querySelectorAll('.button-select-widget .btn'), function (elem) { if (!elem._hasButtonSelectEvent) { elem.addEventListener('click', buttonClick, false); elem._hasButtonSelectEvent = true; } }); </script> ''' output = [ format_html('<div{0}>', flatatt(final_attrs)), format_html('<input{0} type="hidden">', flatatt(input_attrs)), options, '</div>', js, ] return mark_safe('\n'.join(output))
def render(self, name, value, attrs=None): from django.contrib.staticfiles.storage import staticfiles_storage extra_attrs = dict(attrs) extra_attrs.update({ 'name': name, 'class': 'djng-{}-uploader'.format(self.filetype), 'djng-fileupload-url': self.fileupload_url, 'ngf-drop': 'uploadFile($file, "{0}", "{id}", "{ng-model}")'.format(self.filetype, **attrs), 'ngf-select': 'uploadFile($file, "{0}", "{id}", "{ng-model}")'.format(self.filetype, **attrs), }) self.update_attributes(extra_attrs, value) if DJANGO_VERSION < (1, 11): final_attrs = self.build_attrs(extra_attrs=extra_attrs) else: final_attrs = self.build_attrs(self.attrs, extra_attrs=extra_attrs) elements = [format_html('<textarea {}>{}</textarea>', flatatt(final_attrs), self.area_label)] # add a spinnging wheel spinner_attrs = { 'class': 'glyphicon glyphicon-refresh glyphicon-spin', 'ng-cloak': True, } elements.append(format_html('<span {}></span>', flatatt(spinner_attrs))) # add a delete icon icon_attrs = { 'src': staticfiles_storage.url('djng/icons/{}/trash.svg'.format(self.filetype)), 'class': 'djng-btn-trash', 'title': _("Delete File"), 'djng-fileupload-button ': True, 'ng-click': 'deleteImage("{id}", "{ng-model}")'.format(**attrs), 'ng-cloak': True, } elements.append(format_html('<img {} />', flatatt(icon_attrs))) # add a download icon if value: download_attrs = { 'href': value.url, 'class': 'djng-btn-download', 'title': _("Download File"), 'download': True, 'ng-cloak': True, } download_icon = staticfiles_storage.url('djng/icons/{}/download.svg'.format(self.filetype)) elements.append(format_html('<a {}><img src="{}" /></a>', flatatt(download_attrs), download_icon)) return format_html('<div class="drop-box">{}</div>', mark_safe(''.join(elements)))
def render(self, name, value, attrs=None): if value is None: value = '' store_id = self.get_store_id(getattr(attrs, "id", None), name) final_attrs = self.build_attrs(attrs, type=self.input_type, name=name, store=store_id) if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_str(self._format_value(value)) self.store_attrs.update({ 'dojoType': self.store, 'url': self.url, 'jsId':store_id }) # TODO: convert store attributes to valid js-format (False => false, dict => {}, array = []) store_node = '<div%s></div>' % flatatt(self.store_attrs) return mark_safe('%s<input%s />' % (store_node, flatatt(final_attrs)))
def render(self, name, value, attrs=None): attrs = attrs or {} ace_attrs = { 'class': 'django-ace-widget loading', 'style': 'width:%s; height:%s' % (self.width, self.height), 'id': 'ace_%s' % name, } if self.mode: ace_attrs['data-mode'] = self.mode if self.theme: ace_attrs['data-theme'] = self.theme if self.wordwrap: ace_attrs['data-wordwrap'] = 'true' attrs.update(style='width: 100%; min-width: 100%; max-width: 100%; resize: none') textarea = super(AceWidget, self).render(name, value, attrs) html = '<div%s><div></div></div>%s' % (flatatt(ace_attrs), textarea) # add toolbar html = ('<div class="django-ace-editor"><div style="width: 100%%" class="django-ace-toolbar">' '<a href="./" class="django-ace-max_min"></a></div>%s</div>') % html return mark_safe(html)
def render(self, name, value, attrs=None, choices=()): # css class currently breaks the layout for some reason, self.attrs.pop('class', None) final_attrs = self.build_attrs(attrs, name=name) selected = [] if value is None else value options = self.render_options(choices, selected) if self.add_item_link is not None: final_attrs['add_item_link'] = urlresolvers.reverse( self.add_item_link ) if self.max_items is not None: final_attrs['max_items'] = self.max_items if self.allocated_filter: final_attrs['allocated_filter'] = "True" final_attrs['allocated_help_text'] = self.allocated_help_text final_attrs['available_help_text'] = self.available_help_text final_attrs['no_allocated_text'] = self.no_allocated_text final_attrs['no_available_text'] = self.no_available_text open_tag = format_html('<d-table {}>', flatatt(final_attrs)) output = [open_tag, options, '</d-table>'] return mark_safe('\n'.join(output))
def render(self, context): """ Build the filepath by appending the extension. """ module_path = self.path.resolve(context) if not settings.SYSTEMJS_ENABLED: if settings.SYSTEMJS_DEFAULT_JS_EXTENSIONS: name, ext = posixpath.splitext(module_path) if not ext: module_path = '{}.js'.format(module_path) if settings.SYSTEMJS_SERVER_URL: tpl = """<script src="{url}{app}" type="text/javascript"></script>""" else: tpl = """<script type="text/javascript">System.import('{app}');</script>""" return tpl.format(app=module_path, url=settings.SYSTEMJS_SERVER_URL) # else: create a bundle rel_path = System.get_bundle_path(module_path) url = staticfiles_storage.url(rel_path) tag_attrs = {'type': 'text/javascript'} for key, value in self.tag_attrs.items(): if not isinstance(value, bool): value = value.resolve(context) tag_attrs[key] = value return """<script{attrs} src="{url}"></script>""".format( url=url, attrs=flatatt(tag_attrs) )
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): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs) final_attrs['name'] = name assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'" mce_config = self.profile.copy() #mce_config.update(get_language_config(self.content_language)) #if tinymce.settings.USE_FILEBROWSER: #mce_config['file_browser_callback'] = "djangoFileBrowser" mce_config.update(self.mce_attrs) mce_config['selector'] = '#%s' % final_attrs['id'] # Fix for js functions #js_functions = {} #for k in ('paste_preprocess','paste_postprocess'): #if k in mce_config: #js_functions[k] = mce_config[k] #del mce_config[k] mce_json = json.dumps(mce_config) html = render_to_string('tinymce/widget.html', { 'mce_config': mce_config, 'mce_json': mce_json, 'attrs': flatatt(final_attrs), 'value': escape(value), 'id': final_attrs.get('id'), }) return mark_safe(html)
def test_flatatt_no_side_effects(self): """ flatatt() does not modify the dict passed in. """ attrs = {'foo': 'bar', 'true': True, 'false': False} attrs_copy = copy.copy(attrs) self.assertEqual(attrs, attrs_copy) first_run = flatatt(attrs) self.assertEqual(attrs, attrs_copy) self.assertEqual(first_run, ' foo="bar" true') second_run = flatatt(attrs) self.assertEqual(attrs, attrs_copy) self.assertEqual(first_run, second_run)
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 # Only add the suffix if the label does not end in punctuation. label_suffix = label_suffix if label_suffix is not None else self.form.label_suffix # 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("{0}{1}", 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{0}>{1}</label>", attrs, contents) else: contents = conditional_escape(contents) return mark_safe(contents)
def render(self, name, value, attrs=None): attrs_for_textarea = attrs.copy() attrs_for_textarea["hidden"] = "true" html = super(SummernoteWidget, self).render(name, value, attrs_for_textarea) final_attrs = self.build_attrs(attrs) del final_attrs["id"] # Use original attributes without id. contexts = self.template_contexts() url = reverse("django_summernote-editor", kwargs={"id": attrs["id"]}) html += render_to_string( "django_summernote/widget_iframe.html", { "id": attrs["id"].replace("-", "_"), "id_src": attrs["id"], "src": url, "attrs": flatatt(final_attrs), "width": contexts["width"], "height": contexts["height"], "settings": json.dumps(contexts), "STATIC_URL": settings.STATIC_URL, }, ) return mark_safe(html)
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, **kwargs): if value is None: value = '' if not attrs: attrs = self.attrs else: attrs.update(self.attrs) if DJANGO_GTE_1_11: final_attrs = self.build_attrs( attrs, extra_attrs={'name': name} ) else: final_attrs = self.build_attrs(attrs, name=name) return format_html( '<div class="markdown-widget-wrapper">' '<textarea{}>\r\n{}</textarea>' '<div class="markdown-preview">Preview</div>' '</div>', flatatt(final_attrs), safe_text(value) )
def render(self, name, value, attrs=None, **kwargs): summernote_settings = self.summernote_settings() summernote_settings.update(self.attrs.get('summernote', {})) html = super(SummernoteWidget, self).render(name, value, attrs=attrs, **kwargs) context = { 'id': attrs['id'], 'id_safe': attrs['id'].replace('-', '_'), 'flat_attrs': flatatt(self.final_attr(attrs)), 'settings': json.dumps(summernote_settings), 'src': reverse('django_summernote-editor', kwargs={'id': attrs['id']}), # Width and height have to be pulled out to create an iframe with correct size 'width': summernote_settings['width'], 'height': summernote_settings['height'], } html += render_to_string('django_summernote/widget_iframe.html', context) return mark_safe(html)
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>') quick_add_button = """ <span class="quick-add-btn"> <a class="btn" data-url="%s?mode=iframe&quick_add_target=%s" data-toggle="popover" data-placement="bottom" data-trigger="hover" data-content="%s"> <i class="fa fa-plus text-primary"></i> </a> </span> """.strip() output.append(quick_add_button % (self.url, name, _("Create New"))) return mark_safe('\n'.join(output))
def render(self, name, value, attrs=None, choices=()): if value is None: value = '' if 'class' not in attrs: attrs['class'] = 'jstree' else: attrs['class'] += ' jstree' final_attrs = self.build_attrs(attrs, name=name) output = [] output.append(format_html('<div{0}>', flatatt(final_attrs))) options = self.render_options(choices, [value]) if options: output.append(options) output.append('</div>') hidden = super(JSTreeWidget, self).render(name, value, attrs) output.append(hidden) output.append('<script>$(document).ready(function(){{$("div#{0}").' 'jstree(true).select_node("{1}");}});</script>' .format(attrs['id'], value)) return mark_safe('\n'.join(output))
def render(name, value=None, attrs=None): if not isinstance(value, (list, tuple)): value = [value] values = value # The tag is a marker for our javascript to reshuffle the elements. This is because some widgets have complex rendering with multiple fields pieces = [ '<{tag} {multi_attr}>{widget}</{tag}>'.format( tag='div', multi_attr=config.WOOEY_MULTI_WIDGET_ATTR, widget=render_func(name, value, attrs)) for value in values ] # we add a final piece that is our button to click for adding. It's useful to have it here instead of the template so we don't # have to reverse-engineer who goes with what # build the attribute dict data_attrs = flatatt( appender_data_dict if appender_data_dict is not None else {}) pieces.append( format_html( '<a href="#{anchor}"{data}><span class="glyphicon glyphicon-plus"></span></a>', anchor=config.WOOEY_MULTI_WIDGET_ANCHOR, data=data_attrs)) return mark_safe('\n'.join(pieces))
def create_aria_hidden_label_tag(field, attrs): ''' A <label> for sighted users only. Sighted users will see this instead of <legend> for groups of sub-widgets because it's easier to visually style. It can't include a 'for' attribute because the attribute will likely be duplicated in the sub-widget grouping, which can confuse browsers because multiple labels for the same id will exist. Other than that, much of this code is taken from Django's implementation of BoundField.label_tag(). ''' attrs = {'aria_hidden': 'true', **attrs} if field.field.required and hasattr(field.form, 'required_css_class'): if 'class' in attrs: attrs['class'] += ' ' + field.form.required_css_class else: attrs['class'] = field.form.required_css_class attrs = flatatt(attrs) return SafeString(format_html('<label{}>{}</label>', attrs, field.label))
def render(self, name, value, attrs=None, renderer=None): if renderer is None: renderer = get_default_renderer() if value is None: value = "" final_attrs = self.build_attrs(self.attrs, attrs, name=name) self._set_config() external_plugin_resources = [ [force_str(a), force_str(b), force_str(c)] for a, b, c in self.external_plugin_resources ] return mark_safe( renderer.render( "ckeditor/widget.html", { "final_attrs": flatatt(final_attrs), "value": conditional_escape(force_str(value)), "id": final_attrs["id"], "config": json_encode(self.config), "external_plugin_resources": json_encode(external_plugin_resources), }, ) )
def render(self, name, value, attrs=None, renderer=None): date_format = "yyyy-MM-dd" if "format" not in self.attrs: attrs['format'] = date_format if "data-format" not in self.attrs: attrs['data-format'] = date_format field = super(DatepickerInput, self).render(name, value, attrs) final_attrs = self.build_attrs(attrs) output = format_html( u''' <div class="input-append date datepicker" data-provide="datepicker" {0}> {1} <span class="add-on"> <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i> </span> </div> ''', flatatt(final_attrs), field) return mark_safe(output)
def render(self, name, value, attrs=None): attrs = attrs or {} ace_attrs = { "class": "django-ace-widget loading", "style": "width:%s; height:%s" % (self.width, self.height) } if self.mode: ace_attrs["data-mode"] = self.mode if self.theme: ace_attrs["data-theme"] = self.theme if self.wordwrap: ace_attrs["data-wordwrap"] = "true" if self.minlines: ace_attrs["data-minlines"] = str(self.minlines) if self.maxlines: ace_attrs["data-maxlines"] = str(self.maxlines) ace_attrs["data-showprintmargin"] = ( "true" if self.showprintmargin else "false" ) textarea = super(AceWidget, self).render(name, value, attrs) html = '<div%s><div></div></div>%s' % (flatatt(ace_attrs), textarea) # add toolbar toolbar = ('<div class="django-ace-editor">' '<div style="width: %s" class="django-ace-toolbar">' '<a href="./" class="django-ace-max_min"></a>' '</div>%s</div>') html = toolbar % (self.width, html) return mark_safe(html)
def render(self, name, value, attrs=None, renderer=None): if value is None: value = '' value = smart_text(value) final_attrs = attrs.copy() final_attrs['name'] = name final_attrs['class'] = 'tinymce' assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'" mce_config = self.get_mce_config(final_attrs) mce_json = self.get_mce_json(mce_config) if tinymce_settings.USE_COMPRESSOR: compressor_config = { 'plugins': mce_config.get('plugins', ''), 'themes': mce_config.get('theme', 'advanced'), 'languages': mce_config.get('language', ''), 'diskcache': True, 'debug': False, } final_attrs['data-mce-gz-conf'] = json.dumps(compressor_config) final_attrs['data-mce-conf'] = mce_json html = [ '<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value)) ] return mark_safe('\n'.join(html))
def render(self, name, value, attrs=None, choices=()): # make sure the url exists try: url = force_text(self.url) except NoReverseMatch: url = None if not url: return "" if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) if self.model: final_attrs['data-model'] = self.model choices = [] output = [format_html('<select{}>', flatatt(final_attrs))] options = self.render_options(choices, [value]) if options: output.append(options) output.append('</select>') quick_add_button = """ <span class="quick-add-btn"> <a class="btn btn-inverse" data-url="%s?mode=iframe&quick_add_target=%s" data-toggle="popover" data-placement="bottom" data-trigger="manual" data-content="%s"> <i class="fa fa-plus text-primary"></i> </a> </span> """.strip() output.append(quick_add_button % (self.url, name, _("Create New"))) return mark_safe('\n'.join(output))
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(self.attrs, attrs, name=name) self._set_config() external_plugin_resources = [[ force_text(a), force_text(b), force_text(c) ] for a, b, c in self.external_plugin_resources] return mark_safe( render_to_string( 'ckeditor/widget.html', { 'final_attrs': flatatt(final_attrs), 'value': conditional_escape(force_text(value)), 'id': final_attrs['id'], 'config': json_encode(self.config), 'external_plugin_resources': json_encode(external_plugin_resources) }))
def render(self, name, value, attrs=None): value = value or '' final_attrs = self.build_attrs(attrs) self.html_id = final_attrs.pop('id', name) current_repr = '' initial = None lookup = get_lookup(self.channel) if value: objs = lookup.get_objects([value]) try: obj = objs[0] except IndexError: raise Exception("%s cannot find object:%s" % (lookup, value)) current_repr = lookup.format_item_display(obj) initial = [current_repr, obj.pk] if self.show_help_text: help_text = self.help_text else: help_text = '' context = { 'name': name, 'html_id': self.html_id, 'current_id': value, 'current_repr': current_repr, 'help_text': help_text, 'extra_attrs': mark_safe(flatatt(final_attrs)), 'func_slug': self.html_id.replace("-", ""), 'add_link': self.add_link, } context.update(plugin_options(lookup, self.channel, self.plugin_options, initial)) out = render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'), context) return mark_safe(out)
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()) ) #Write by Kaajavi summary = "Raw passwords are not stored, so there is no way to see this \ user's password, but you can change the password using \ <a href=\"../password/\">this form</a>." return format_html("<div{}>{}</div>", flatatt(final_attrs), format_html(summary))
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) # Translators: link_start and link_end are HTML tags for a link to the terms of service. # platform_name is the name of this Open edX installation. label = _( 'I, and my company, accept the {link_start}{platform_name} API Terms of Service{link_end}.' ).format( platform_name=configuration_helpers.get_value( 'PLATFORM_NAME', settings.PLATFORM_NAME), link_start='<a href="{url}" target="_blank">'.format( url=reverse('api_admin:api-tos')), link_end='</a>', ) html = '<input{{}} /> <label class="tos-checkbox-label" for="{id}">{label}</label>'.format( id=final_attrs['id'], label=label) return format_html(html, flatatt(final_attrs))
def render(self, name, value, attrs=None, renderer=None): if not isinstance(value, basestring): value = json.dumps(value) input_attrs = {'hidden': True} input_attrs.update(attrs) if 'class' not in input_attrs: input_attrs['class'] = 'for_jsoneditor' else: input_attrs['class'] += ' for_jsoneditor' r = super(JSONEditor, self).render(name, value, input_attrs) div_attrs = {} div_attrs.update(attrs) div_attrs.update({'id': (attrs['id'] + '_jsoneditor')}) if version.parse(django.get_version()) >= version.parse("1.11"): final_attrs = self.build_attrs(div_attrs, extra_attrs={'name': name}) else: final_attrs = self.build_attrs(div_attrs, name=name) r += ''' <div %(attrs)s></div> ''' % { 'attrs': flatatt(final_attrs), } return mark_safe(r)
def test_flatatt(self): ########### # flatatt # ########### self.assertEqual(flatatt({'id': "header"}), ' id="header"') self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"') self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': "required"}), ' class="news" required="required" title="Read this"' ) self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': True}), ' class="news" title="Read this" required' ) self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': False}), ' class="news" title="Read this"' ) self.assertEqual(flatatt({}), '')
def render(self, name, value, attrs=None, choices=()): attrs.update(activity='activity', name=name) if value: attrs['leader-ids'] = json.dumps(value) final_attrs = flatatt(self.build_attrs(self.attrs, attrs)) return format_html('<leader-select {}></leader-select>', final_attrs)
def dropdown(menu_id, labelled_by=None): attrs = {'class': 'dropdownMenu', 'role': 'menu', 'id': menu_id} if labelled_by: attrs['aria-labelledby'] = labelled_by return format_html(u'<ul{}>', flatatt(attrs))
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 render(self, name, value, attrs=None, renderer=None): attrs.update(program='program', name=name) if value: attrs['leader-ids'] = json.dumps(value) final_attrs = flatatt(self.build_attrs(self.attrs, attrs)) return format_html('<leader-select {}></leader-select>', final_attrs)
def tag(self, attrs=None): attrs = attrs or self.attrs final_attrs = dict(attrs, name=self.name, value=self.choice_value) if self.is_checked(): final_attrs['checked'] = 'checked' return format_html('<button{}>{}</button>', flatatt(final_attrs), self.choice_label)
def render(self, name, value, attrs=None, renderer=None): output = super().render(name, value, attrs) add_css_classes_to_dict(attrs, 'optional-input-wrap form-control') return format_html('<div {}>{}</div>', flatatt(attrs), output)
def render_scalar(self, final_attrs, value, display_value): return format_html('<span{}>{}</span>', flatatt(final_attrs), self.get_text(display_value))
def transform_option_html_attrs(self, option_label): if not callable(self.transform_html_attrs): return '' return flatatt(self.transform_html_attrs(option_label))
def render(self): attrs = {'href': self.url, 'class': ' '.join(sorted(self.classes))} attrs.update(self.attrs) return format_html('<a{}>{}</a>', flatatt(attrs), self.label)
def render(self, name, value, attrs=None, choices=()): attrs.update(name=name) final_attrs = self.build_attrs(self.attrs, attrs) return format_html('<participant-select {}></participant-select>', flatatt(final_attrs))
def render(self, name, value, attrs=None): attrs.update(self.attrs) return format_html('<div{0}>{1}</div>', flatatt(attrs), value)
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)))