def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) field_id = kwargs.pop('id') kwargs.setdefault('name', field.name) field_name = kwargs.pop('name') kwargs.pop('type', None) value = kwargs.pop('value', None) if value is None: value = field._value() if not value: value = '' date_fmt = kwargs.pop('format', None) if date_fmt is not None: date_fmt = date_fmt.replace("%", "")\ .replace("d", "dd")\ .replace("m", "mm")\ .replace("Y", "yyyy") else: date_fmt = get_locale().date_formats['short'].pattern date_fmt = babel2datepicker(date_fmt) date_fmt = date_fmt.replace('M', 'm') # force numerical months s = u'<div {}>\n'.format(html_params( **{'class': "input-group date", 'data-provide': 'datepicker', 'data-date': value, 'data-date-format': date_fmt})) s += u' <input size="13" type="text" class="form-control" {} />\n'.format( html_params(name=field_name, id=field_id, value=value)) s += u' <span class="input-group-addon"><i class="icon-calendar"></i></span>\n' s += u'</div>\n' return Markup(s)
def checkbox_button(field, **kwargs): """custom wtforms widget for the checkbox button toggle stuff""" kwargs.setdefault('type', 'checkbox') value = field.data field_id = kwargs.pop('id', field.id) button_id = "%s-%s" %(field_id, field_id) hidden_params = { 'type' : 'hidden', 'id' : field_id, 'name' : field.name, 'value' : "1" if value else "0" } button_params = { 'id' : button_id, 'for' : field_id, } if value: button_params['class'] = "btn btn-toggle active" else: button_params['class'] = "btn btn-toggle" if "class" in kwargs: button_params['class'] = button_params['class'] + " " + kwargs['class'] html = [ u'<input %s />' %html_params(**hidden_params), u'<button %s >' %html_params(**button_params) ] if value: html.append(u'<i class="icon icon-ok icon-nok"></i> ') else: html.append(u'<i class="icon icon-nok"></i> ') html.append(field.label.text) html.append(u"</button>") return u''.join(html)
def __call__(self, field, **kwargs): if field.data: previous_markup = """ <label><input {attr} /> {field.data.file_name}</label> """.format( field=field, attr=html_params(**{ 'id': field.id + '-previous', 'class_': 'js-fileinput-previous', 'type': 'checkbox', 'name': field.name + '-previous', 'value': '1', 'checked': True, 'data-fileinput-new': '#{}-new'.format(field.id) })) else: previous_markup = '' upload_markup = '<input {attr} />'.format( attr=html_params(**{ 'id': field.id + '-new', 'type': 'file', 'name': field.name + '-new', 'class_': 'file js-fileinput-new', 'data-initial-caption': 'Upload new file...', 'data-show-upload': 'false', 'data-show-preview': 'false', 'data-fileinput-previous': '#{}-previous'.format(field.id) })) markup = previous_markup + upload_markup return markup
def select_multi_checkbox(field, ul_class='', **kwargs): '''Custom multi-select widget for vendor documents needed Returns: SelectMulti checkbox widget with tooltip labels ''' kwargs.setdefault('type', 'checkbox') field_id = kwargs.pop('id', field.id) html = [u'<div %s>' % widgets.html_params(id=field_id, class_=ul_class)] # if we don't have any field data, set it to an empty list # to avoid a rendering TypeError if field.data is None: field.data = [] for value, label, _ in field.iter_choices(): name, description, href = label choice_id = u'%s-%s' % (field_id, value) options = dict(kwargs, name=field.name, value=value, id=choice_id) if int(value) in field.data: options['checked'] = 'checked' html.append(u'<div class="checkbox">') html.append(u'<input %s /> ' % widgets.html_params(**options)) html.append(u'<label for="%s">%s</label>' % (choice_id, build_label_tooltip(name, description))) html.append(u'</div>') html.append(u'</div>') return u''.join(html)
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) html = ['<select %s>' % html_params(name=field.name, **kwargs)] for val, label, selected in field.iter_choices(): html.append(self.render_option(val, label, selected)) html.append('</select>') html.append('<input type=text style="display: none" {0} {1} >' .format(html_params(name=field.name+"_input"), html_params(id=field.name+"_input"))) return HTMLString(''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) name = "%s.png" % field.name url = kwargs.get("url", "%s/%s" % (kwargs.get("path"), name)) kwargs.setdefault("value", name) preview = HTMLString(u"<img %s />" % html_params(name="preview_"+name, src=url)) inputButton = HTMLString(u"<input %s />" % html_params(name=field.name, type=u"file", **kwargs)) return preview + inputButton
def render_subfield(self, subfield, **kwargs): html = [] html.append("<div %s>" % html_params(class_='row')) # Field html.append(subfield()) # Buttons html.append("<div %s>%s</div>" % ( html_params(class_='col-xs-2'), self._sort_button() + self._remove_button() )) html.append("</div>") return ''.join(html)
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) sub_kwargs = dict((k[4:],v) for k, v in kwargs.iteritems() if k.startswith(self.sub_startswith)) kwargs = dict(filter(lambda x: not x[0].startswith(self.sub_startswith), kwargs.iteritems())) sub_html = '%s %s' % (self.sub_tag, html_params(**sub_kwargs)) html = ['<%s %s>' % (self.html_tag, html_params(**kwargs))] for subfield in field: if self.prefix_label: html.append('<%s>%s %s</%s>' % (sub_html, subfield.label, subfield(), self.sub_tag)) else: html.append('<%s>%s %s</%s>' % (sub_html, subfield(), subfield.label, self.sub_tag)) html.append('</%s>' % self.html_tag) return HTMLString(''.join(html))
def select_multi_checkbox(field, ul_class='', ul_role='', **kwargs): kwargs.setdefault('type', 'checkbox') field_id = kwargs.pop('id', field.id) html = [u'<ul %s>' % html_params(id=field_id, class_=ul_class, role=ul_role)] for value, label, checked in field.iter_choices(): choice_id = u'%s-%s' % (field_id, value) options = dict(kwargs, name=field.name, value=value, id=choice_id) if checked: options['checked'] = 'checked' html.append(u'<li><input %s /> ' % html_params(**options)) html.append(u'<label for="%s">%s</label></li>' % (field_id, label)) html.append(u'</ul>') return u''.join(html)
def _add_field_widget(field, **kwargs): # spoof field_name in context of it's form field_name = "{}{}".format( field._prefix, field.short_name, ) # render child fields (which should be wrapped w/ delete widgets) wrapper_id = "{}_wrapper".format(field_name) html_string = "<div {}>".format(html_params(id=wrapper_id)) for subfield in field: html_string += subfield.widget(subfield, **kwargs) html_string += "</div>" # render a hidden template of the subfields template_id = "{}_template".format(field_name) subform_tmpl_kwargs = { "id": template_id, "style": "display: none;", } html_string += "<div {}>".format(html_params(**subform_tmpl_kwargs)) tmpl_prefix = "{0}-!{0}!".format(field_name) tmpl_field = field.unbound_field.bind(form=None, name=tmpl_prefix, prefix="", _meta=field.meta) tmpl_field.process(formdata=None, data={}) tmpl_field.widget = deleteable_widget_wrapper(tmpl_field.widget) html_string += tmpl_field.widget(tmpl_field) html_string += "</div>" # create function that duplicates the template field field_name_regex = field_name.replace("-", "\-").replace("_", "\_") tmpl_regex = "\!+{0}+\!".format(field_name_regex) onclick = """ $("#{0}").append( $("#{1}").clone() // Duplicate subform from template .show() // Display the duplicated subform .html( // rewrite HTML of new subform $('#{1}').html() .replace(new RegExp('{2}', 'g'), (new Date).getTime().toString()) ) .attr('id', '') // remove #subform_template from new subform );""".format(wrapper_id, template_id, tmpl_regex) new_link_params = html_params( href="javascript:void(0)", onclick=onclick, ) html_string += "<a {}>".format(new_link_params) html_string += "New" html_string += "</a>" return HTMLString(html_string)
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) field_id = kwargs.pop('id') kwargs.pop('type', None) value = kwargs.pop('value', None) if value is None: value = field._value() if not value: value = ' ' date_value, time_value = value.split(' ', 1) return Markup(u'<input type="date" data-datepicker="datepicker" %s /> <input type="time" data-provide="timepicker" %s />' % ( html_params(name=field.name, id=field_id + '-date', value=date_value, **kwargs), html_params(name=field.name, id=field_id + '-time', value=time_value, **kwargs) ))
def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) kwargs.setdefault("name", field.name) template = self.data_template if field.data else self.empty_template return HTMLString( template % { "text": html_params(type="text", value=field.data), "file": html_params(type="file", **kwargs), "marker": "_%s-delete" % field.name, } )
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) kwargs.setdefault('name', field.name) template = self.data_template if field.data else self.empty_template return HTMLString(template % { 'text': html_params(type='text', readonly='readonly', value=field.data), 'file': html_params(type='file', **kwargs), 'marker': '_%s-delete' % field.name })
def __call__(self, field, title='', **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = 'multiple' html = [u'<select %s>' % html_params(name=field.name, **kwargs)] for val, label, selected in field.iter_choices(): options = {'value': val} if selected: options['selected'] = u'selected' if val is not None or val != '_None': options['title'] = url('/images/flags/%s.png' % str(val)) html.append(u'<option %s>%s</option>' % (html_params(**options), escape(unicode(label)))) html.append(u'</select>') return u''.join(html)
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) sub_kwargs = dict((k[4:], v) for k, v in kwargs.iteritems() if k.startswith(self.sub_startswith)) kwargs = dict(filter(lambda x: not x[0].startswith(self.sub_startswith), kwargs.iteritems())) sub_html = '%s %s' % (self.sub_tag, html_params(**sub_kwargs)) left = ['<%s %s>' % (self.html_tag, html_params(id='%s-left' % field.id, class_='drag-left drag-part'))] right = ['<%s %s>' % (self.html_tag, html_params(id='%s-right' % field.id, class_='drag-right drag-part'))] for subfield in field: if subfield.checked: right.append('<%s>%s %s</%s>' % (sub_html, subfield.label, subfield(), self.sub_tag)) else: left.append('<%s>%s %s</%s>' % (sub_html, subfield(), subfield.label, self.sub_tag)) left.append('</%s>' % self.html_tag) right.append('</%s>' % self.html_tag) html = """<div class="drag-select">%s%s</div><script type="text/javascript"> $(function() { function initClick(id) { $('#' + id + '-left > div, #' + id + 'right > div').click(function () {}) $('#' + id + '-left > div').unbind('click').click(function () { $(this).find('input[type="checkbox"]').get(0).checked = true; $('#' + id + '-right').append($(this).clone()) $(this).remove() initClick(id); }) $('#' + id + '-right > div').unbind('click').click(function () { $(this).find('input[type="checkbox"]').removeAttr('checked'); $('#' + id + '-left').append($(this).clone()) $(this).remove() initClick(id); }) } function init(id) { dragula([document.getElementById(id + '-left'), document.getElementById(id + '-right')]) .on('drop', function (el, target) { if (target === document.getElementById(id + '-left')) { $(el).find('input[type="checkbox"]').removeAttr('checked'); } else { $(el).find('input[type="checkbox"]').get(0).checked = true; } initClick(id) }) initClick(id); } init('%s') }); </script>""" % (''.join(left), ''.join(right), field.id) return HTMLString(html)
def render_option(cls, value, label, mixed): """ Renders an option as the appropriate element, but wraps options into an ``optgroup`` tag if the ``label`` parameter is ``list`` or ``tuple``. The last option, mixed, differs from "selected" in that it is a tuple containing the coercion function, the current field data, and a flag indicating if the associated field supports multiple selections. """ # See if this label is actually a group of items if isinstance(label, (list, tuple)): children = [] # Iterate on options for the children. for item_value, item_label in label: item_html = cls.render_option(item_value, item_label, mixed) children.append(item_html) html = u"<optgroup %s>%s</optgroup>\n" data = (html_params(label=unicode(value)), u"".join(children)) else: # Get our coercion function, the field data, and # a flag indicating if this is a multi-select from the tuple coerce_func, fielddata, multiple = mixed # See if we have field data - if not, don't bother # to see if something's selected. if fielddata is not None: # If this is a multi-select, look for the value # in the data array. Otherwise, look for an exact # value match. if multiple: selected = coerce_func(value) in fielddata else: selected = coerce_func(value) == fielddata else: selected = False options = {"value": value} if selected: options["selected"] = True html = u"<option %s>%s</option>\n" data = (html_params(**options), escape(unicode(label))) return HTMLString(html % data)
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = 'multiple' html = [u'<select %s>' % html_params(name=field.name, **kwargs)] for value, label, selected in field.iter_choices(): if hasattr(label, '__iter__'): html.append(u'<optgroup %s>' % html_params(label=value)) for v, l, s in label: html.append(self.render_option(v, l, s)) html.append(u'</optgroup>') else: html.append(self.render_option(value, label, selected)) html.append(u'</select>') return HTMLString(u''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) kwargs.setdefault("name", field.name) args = {"file": html_params(type="file", **kwargs), "marker": "_%s-delete" % field.name} if field.data and isinstance(field.data, string_types): url = self.get_url(field) args["image"] = html_params(src=url) template = self.data_template else: template = self.empty_template return HTMLString(template % args)
def scopes_multi_checkbox(field, **kwargs): """Render multi checkbox widget.""" kwargs.setdefault('type', 'checkbox') field_id = kwargs.pop('id', field.id) html = ['<div class="row">'] for value, label, checked in field.iter_choices(): choice_id = u'%s-%s' % (field_id, value) options = dict( kwargs, name=field.name, value=value, id=choice_id, class_=' ', ) if checked: options['checked'] = 'checked' html.append(u'<div class="col-md-3">') html.append(u'<label for="%s" class="checkbox-inline">' % field_id) html.append(u'<input %s /> ' % widgets.html_params(**options)) html.append("%s <br/><small class='text-muted'>%s</small>" % ( value, label.help_text) ) html.append(u'</label></div>') html.append(u'</div>') return HTMLString(u''.join(html))
def dropbox_widget(field, **kwargs): """Create Dropbox widget.""" field_id = kwargs.pop('id', field.id) html = [u'<input type="dropbox-chooser"\ name="fileurl"\ style="visibility: hidden;"\ data-link-type="direct"\ id="db-chooser"/></br> \ <div class="pluploader" %s > \ <table id="file-table" class="table table-striped table-bordered" \ style="display:none;">\ <thead>\ <tr>\ <th>Filename</th>\ <th>Size</th>\ <th>Status</th>\ <td></td>\ </tr>\ </thead>\ <tbody id="filelist">\ </tbody>\ </table>\ <a class="btn btn-success disabled" id="uploadfiles"> \ <i class="glyphicon glyphicon-upload"></i> Start upload</a>\ <a class="btn btn-danger" id="stopupload" style="display:none;">\ <i class="glyphicon glyphicon-stop"></i> Cancel upload</a>\ <span id="upload_speed" class="pull-right"></span>\ <div id="upload-errors"></div>\ </div>' % html_params(id=field_id)] return HTMLString(u''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) kwargs['class'] = 'wysiwyg' return HTMLString('<textarea %s>%s</textarea>' % ( html_params(name=field.name, **kwargs), escape(text_type(field._value()), quote=False) ))
def __call__(self, field, **kwargs): # TODO use a more advanced library, such as: # http://brutaldesign.github.io/swipebox if "class" in kwargs: kwargs["class"] = " ".join(["img-responsive", kwargs["class"]]) else: kwargs["class"] = "img-responsive" # TODO shrink using class, and proportinalize if self.size_type == Image.SMALL: kwargs['style'] = 'max-width: 128px; max-height: 128px' elif self.size_type == Image.NORMAL: kwargs['style'] = 'max-width: 256px; max-height: 256px' html = ('<a href="%s" class="fancybox thumbnail" rel="group"' 'title="%s"><img %s /></a>') # why do this? force browser to refresh the images value = field._value() if isinstance(value, basestring): value = [value] htmls = [] for url in value: params = {'random': random_str()} url_parts = list(urlparse.urlparse(url)) query = dict(urlparse.parse_qsl(url_parts[4])) query.update(params) url_parts[4] = urllib.urlencode(query) url = urlparse.urlunparse(url_parts) htmls.append(HTMLString(html % (url, field.label.text, html_params(src=url, alt=field.label.text, **kwargs)))) return ''.join(htmls)
def date_widget(field, **kwargs): """Create datepicker widget.""" field_id = kwargs.pop('id', field.id) html = [u'<div class="row"><div class="col-xs-5 col-sm-3">' '<input class="datepicker form-control" %s type="text"></div></div' % html_params(id=field_id, name=field_id, value=field.data or '')] return HTMLString(u''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault("value", "") kwargs.setdefault("id", FIELD_NAME) return widgets.HTMLString( "<input {params}></input>".format(params=widgets.html_params(name=field.name, **kwargs)) )
def __call__(self, field, **kwargs): from flask.ext.databrowser.convert import ValueConverter if not self.compressed: html = ["<%s %s>\n" % (self.html_tag, html_params(**kwargs))] if self.rows: for row in self.rows: converter = ValueConverter(row, self.model_view) val = converter(row, self.item_col_spec) if isinstance(getattr(val, "widget", None), Link): html.append(val(**{"class": self.item_css_class})) else: html.append(" <li class=\"%s\" >%s</li>\n" % (self.item_css_class, val())) html.append("</%s>" % self.html_tag) else: uuid_ = uuid.uuid1() if self.rows: html = ['<div class="panel-group">', '<div class="panel panel-default">', '<div class="panel-heading"><h4 class="panel-title">' '<a href="#" data-target="#%s" data-toggle="collapse">%d<i ' 'class="fa fa-chevron-up fa-fw"></i></a></h4></div>' % ( uuid_, len(self.rows)), '<div id="%s" class="panel-collapse collapse list-group" data-builtin="true">' % uuid_] for row in self.rows: converter = ValueConverter(row, self.model_view) html.append(converter(row, self.item_col_spec)(**{"class": "list-group-item"})) html.append('</div>\n</div>\n</div>') else: html = ["0"] return HTMLString(''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault('data-value', kwargs.pop('value', '')) kwargs.setdefault('data-role', 'x-editable') kwargs.setdefault('data-url', './ajax/update/') kwargs.setdefault('id', field.id) kwargs.setdefault('name', field.name) kwargs.setdefault('href', '#') if not kwargs.get('pk'): raise Exception('pk required') kwargs['data-pk'] = str(kwargs.pop("pk")) kwargs['data-csrf'] = kwargs.pop("csrf", "") # subfield is the first entry (subfield) from FieldList (field) subfield = field.entries[0] kwargs = self.get_kwargs(subfield, kwargs) return HTMLString( '<a %s>%s</a>' % (html_params(**kwargs), escape(kwargs['data-value'])) )
def render_option(cls, value, label, mixed): """ Render option as HTML tag, but not forget to wrap options into ``optgroup`` tag if ``label`` var is ``list`` or ``tuple``. """ if isinstance(label, (list, tuple)): children = [] for item_value, item_label in label: item_html = cls.render_option(item_value, item_label, mixed) children.append(item_html) html = u'<optgroup label="%s">%s</optgroup>' data = (escape(unicode(value)), u'\n'.join(children)) else: coerce_func, data = mixed if isinstance(data, list) or isinstance(data, tuple): selected = coerce_func(value) in data else: selected = coerce_func(value) == data options = {'value': value} if selected: options['selected'] = u'selected' html = u'<option %s>%s</option>' data = (html_params(**options), escape(unicode(label))) return HTMLString(html % data)
def __call__(self, field, **kwargs): kwargs['data-role'] = u'select2-ajax' kwargs['data-url'] = url_for('.ajax_lookup', name=field.loader.name) allow_blank = getattr(field, 'allow_blank', False) if allow_blank and not self.multiple: kwargs['data-allow-blank'] = u'1' kwargs.setdefault('id', field.id) kwargs.setdefault('type', 'hidden') if self.multiple: result = [] ids = [] for value in field.data: data = field.loader.format(value) result.append(data) ids.append(as_unicode(data[0])) separator = getattr(field, 'separator', ',') kwargs['value'] = separator.join(ids) kwargs['data-json'] = json.dumps(result) kwargs['data-multiple'] = u'1' else: data = field.loader.format(field.data) if data: kwargs['value'] = data[0] kwargs['data-json'] = json.dumps(data) return HTMLString('<input %s>' % html_params(name=field.name, **kwargs))
def __call__(self, field, **kwargs): html = [] kwargs.setdefault('id', field.id) with_div = True expended = False exp_text = 'style=display:none' if expended else '' if with_div: html.append('<div>') html.append('<span %s>' % widgets.html_params(**kwargs)) hidden = '' html.append('<span class="range-span">') for subfield in field: if subfield.type == 'HiddenField': hidden += text_type(subfield) else: html.append('<div class="range-div">%s%s</div>' % (hidden, text_type(subfield))) hidden = '' html.append('</span>') html.append('<button type="button" class="btn btn-default btn-sm" id="%s-toggle-button" name="%s-toggle-button" style="font-size: 16px;">' % (field.name, field.name)) html.append(' <span></span>') html.append('</button>') html.append('</span>') if with_div: html.append('</div>') if hidden: html.append(hidden) return widgets.HTMLString(''.join(html))
def render_option(cls, value, label, mixed): """ Render option as HTML tag, but not forget to wrap options into ``optgroup`` tag if ``label`` var is ``list`` or ``tuple``. """ if isinstance(label, (list, tuple)): return cls.render_optgroup(value, label, mixed) try: coerce_func, data = mixed except TypeError: selected = mixed else: if isinstance(data, list) or isinstance(data, tuple): selected = coerce_func(value) in data else: selected = coerce_func(value) == data options = {'value': value} if selected: options['selected'] = True html = u'<option %s>%s</option>' data = (html_params(**options), html_escape(six.text_type(label))) return HTMLString(html % data)
def button_widget(field, button_cls="ButtonField btn btn-default", **kwargs): """Render a button widget""" kwargs.setdefault("type", "button") field_id = kwargs.pop("id", field.id) kwargs.setdefault("value", field.label.text) html = [ "<button %s>%s</button>" % (html_params(id=field_id, class_=button_cls), kwargs["value"]) ] return HTMLString("".join(html))
def importdata_button(field, **dummy_kwargs): """Import data button.""" html = u'<button %s data-target="%s">%s</button>' % \ (html_params(id="importData", class_="btn btn-success btn-large", name="importData", type="button"), '#myModal', _('Import')) return HTMLString(html)
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = True html = ['<select %s>' % html_params(name=field.name, **kwargs)] for val, label, display in field.choices: html.append( self.render_option(val, label, val == field.data, display)) html.append('</select>') return HTMLString(''.join(html))
def bootstrap_submit(field, **dummy_kwargs): """Create Bootstrap friendly submit button.""" html = u'<input %s >' % html_params(style="float:right; width: 250px;", id="submitButton", class_="btn btn-primary btn-large", name="submitButton", type="submit", value=field.label.text,) html = [u'<div style="float:right;" >' + html + u'</div>'] return HTMLString(u''.join(html))
def render_option(cls, value, label, selected, **kwargs): if value is True: # Handle the special case of a 'True' value. value = text_type(value) options = dict(kwargs, value=value) if selected: options['selected'] = True return Markup('<option %s>%s</option>' % (html_params(**options), escape(label)))
def __call__(self, field, **kwargs): datas = (field.data or '').split('|') if len(datas) == 3: province, city, county = datas else: province, city, county = '', '', '' province_name = '%s_province' % field.name city_name = '%s_city' % field.name county_name = '%s_county' % field.name return HTMLString(self.template % ( html_params(id=field.name), html_params(id=province_name, name=province_name, **kwargs), html_params(id=city_name, name=city_name, **kwargs), html_params(id=county_name, name=county_name, **kwargs), field.name, province, city, county, ))
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = True html = ['<select %s>' % html_params(name=field.name, **kwargs)] for val, label, selected, html_attribs in field.iter_choices(): html.append( self.render_option(val, label, selected, **html_attribs)) html.append('</select>') return HTMLString(''.join(html))
def render_option(cls, value, label, selected, disabled, **kwargs): if value is True: # Handle the special case of a 'True' value. value = compat.text_type(value) options = dict(kwargs, value=value) if selected: options['selected'] = True if disabled: options['disabled'] = True return widgets.HTMLString('<option %s>%s</option>' % (widgets.html_params(**options), compat.text_type(label)))
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) kwargs.setdefault('name', field.name) if not field.data: field.data = "" template = self.data_template return HTMLString( template % {'text': html_params(type='text', value=field.data, **kwargs)})
def date_widget(field, **kwargs): field_id = kwargs.pop('id', field.id) html = [ u'<input class="datepicker" %s value="" type="text">' % html_params(id=field_id, name=field_id) ] field_class = kwargs.pop('class', '') or kwargs.pop('class_', '') kwargs['class'] = u'datepicker %s' % field_class kwargs['class'] = u'date %s' % field_class return HTMLString(u''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = True html = ['<select %s>' % html_params(name=field.name, **kwargs)] for item1, item2 in field.choices: if isinstance(item2, (list, tuple)): group_label = item1 group_items = item2 html.append('<optgroup %s>' % html_params(label=group_label)) for inner_val, inner_label in group_items: html.append(self.render_option(inner_val, inner_label, field.coerce(inner_val) == field.data)) html.append('</optgroup>') else: val = item1 label = item2 html.append(self.render_option(val, label, val == field.data)) html.append('</select>') return HTMLString(''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = True html = ['<select %s>' % html_params(name=field.name, **kwargs)] for val, label, selected, disabled in field.iter_choices(): extra = disabled and {'disabled': ''} or {} html.append(self.render_option(val, label, selected, **extra)) html.append('</select>') return HTMLString(''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) kwargs.setdefault('name', field.name) args = { 'file': html_params(type='file', **kwargs), 'marker': '_%s-delete' % field.name } if field.data and isinstance(field.data, string_types): url = self.get_url(field) args['image'] = html_params(src=url) template = self.data_template else: template = self.empty_template return HTMLString(template % args)
def open_tag(self, field, **kwargs): """Render open tag.""" html = super(DynamicListWidget, self).open_tag(field, **kwargs) html += """<input %s>""" % html_params( name=field.id + '-__last_index__', id=field.id + '-__last_index__', type="hidden", value=field.last_index, ) return html
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) class_ = kwargs.get('class_', '') class_ = class_ + ' file-uploader' if class_ else 'file-uploader' kwargs['class_'] = class_ return HTMLString('<input %s>' % html_params( name=field.name, type='file', **kwargs ))
def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) kwargs.setdefault("name", field.name) if not field.data: field.data = "" template = self.data_template return HTMLString( template % {"text": html_params(type="text", value=field.data, **kwargs)})
def render_select(cls, part, field): """Render select for a specific part of date.""" yield "<select %s>" % html_params(name=field.name + ":" + part) # If user didn't specifiy the date then the year range will start from current year + 5 years range_value = cls.__current_year + 5 try: current_value = int(getattr(field.data, part)) range_value = current_value + 5 except Exception: current_value = None # TODO: localization yield "<option %s>%s</option>" % (html_params( value="", selected=(current_value is None)), part.capitalize()) option_format = "<option %s>%04d</option>" if part == "year" else "<option %s>%02d</option>" for v in range(range_value, 1912, -1) if part == "year" else range( 1, 13 if part == "month" else 32): yield option_format % (html_params( value=v, selected=(v == current_value)), v) yield "</select>"
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = 'multiple' kwargs['size'] = len( field.choices) if len(field.choices) < 15 else 15 html = ['<select %s>' % widgets.html_params(name=field.name, **kwargs)] for val, label, selected, subtext in field.iter_choices(): html.append(self.render_option(val, label, selected, subtext)) html.append('</select>') return widgets.HTMLString(''.join(html))
def render_option(cls, value, label, selected, disabled, subtext): options = {'value': value} if selected: options['selected'] = 'selected' if disabled: options['disabled'] = 'disabled' if subtext: options['data-subtext'] = subtext return widgets.HTMLString( '<option %s>%s</option>' % (widgets.html_params(**options), escape(unicode(label))))
def geom_formatter(view, value): params = html_params(**{ "data-role": "leaflet", "disabled": "disabled", "data-width": 100, "data-height": 70, "data-geometry-type": value.geom_type, "data-zoom": 15, }) geojson = json.dumps(mapping(value)) return Markup('<textarea %s>%s</textarea>' % (params, geojson))
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) if self.multiple: kwargs['multiple'] = 'multiple' html = [ u'<select %s>' % widgets.html_params(name=field.name, **kwargs) ] for val, label, photo_file_path in field.iter_choices(): html.append(self.render_option(val, label, photo_file_path)) html.append(u'</select>') return widgets.HTMLString(u''.join(html))
def select_multi_checkbox(field, ul_class='', **kwargs): """ 多选框控件 :param field: :param ul_class: :param kwargs: :return: """ kwargs.setdefault('type', 'checkbox') field_id = kwargs.pop('id', field.id) html = [u'<ul %s>' % html_params(id=field_id, class_=ul_class)] for value, label, checked in field.iter_choices(): choice_id = u'%s-%s' % (field_id, value) options = dict(kwargs, name=field.name, value=value, id=choice_id) if checked: options['checked'] = 'checked' html.append(u'<li><input %s /> ' % html_params(**options)) html.append(u'<label for="%s">%s</label></li>' % (field_id, label)) html.append(u'</ul>') return u''.join(html)
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) kwargs.pop('class', None) kwargs.setdefault('style', 'margin: 10px 0;') placeholder = '' if field.data and field.data.filename: placeholder = self.template % dict(name=field.name, filename=field.data.filename) return HTMLString('%s<input %s>' % (placeholder, html_params(name=field.name, type='file', **kwargs)))
def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) kwargs.setdefault("name", field.name) args = { "file": html_params(type="file", **kwargs), } template = self.empty_template return Markup(template % args)
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) html = [u'<ul %s>' % html_params(id=field.id)] data = field.data if data: if not isinstance(data, Iterable): data = unquote(data) params = dict(href=data) html.append(u'<li><a target="_blank" %s>%s</a></li>' % (html_params(**params), self.get_filename(data))) else: for link in data: if link: link = unquote(link) params = dict(href=link) html.append( u'<li ><a target="_blank" %s>%s</a></li>' % (html_params(**params), self.get_filename(link))) html.append(u'</ul>') return HTMLString(u''.join(html))
def bootstrap_reject(field): """ Reject button for hp """ html = u'<input %s >' \ % html_params(id="submitButton", class_="btn btn-danger", name="submitButton", type="submit", value=field.label.text,) return HTMLString(u''.join(html))
def defensedate_widget(field, **kwargs): """Date widget fot thesis.""" field_id = kwargs.pop('id', field.id) html = [ u'<div class="row %s"><div class="col-xs-12">\ <input class="datepicker form-control" %s type="text">\ </div></div>' % (THESIS_CLASS, html_params(id=field_id, name=field_id, value=field.data or '')) ] return HTMLString(u''.join(html))
def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) sub_kwargs = dict((k[4:], v) for k, v in kwargs.iteritems() if k.startswith(self.sub_startswith)) kwargs = dict( filter(lambda x: not x[0].startswith(self.sub_startswith), kwargs.iteritems())) sub_html = '%s %s' % (self.sub_tag, html_params(**sub_kwargs)) html = ['<%s %s>' % (self.html_tag, html_params(**kwargs))] for subfield in field: if self.prefix_label: html.append( '<%s>%s %s</%s>' % (sub_html, subfield.label, subfield(), self.sub_tag)) else: html.append( '<%s>%s %s</%s>' % (sub_html, subfield(), subfield.label, self.sub_tag)) html.append('</%s>' % self.html_tag) return HTMLString(''.join(html))
def currentCheckboxWidget(field, **kwargs): """Current institution checkbox widget.""" field_id = kwargs.pop('id', field.id) html = [ u'<div class="col-md-10 col-margin-top pull-left">\ <input %s %s type="checkbox">\ <label for=%s>Current</label></div>' % (html_params(id=field_id, name=field_id), field.data and "checked" or "", field_id) ] return HTMLString(u''.join(html))
def __call__(self, text=None, **kwargs): kwargs['for'] = self.field_id attributes = widgets.html_params(**kwargs) """ When a label is for a required field it was inserting a * as the label and didnt want it too. This is a super kludgy fix. """ s = widgets.HTMLString('<label %s>%s</label>' % (attributes, text or self.text)) if s.count('*') == 1: s = widgets.HTMLString('<label %s></label>' % (attributes)) return s