def render_options(self, selected_choices): # Normalize to strings. selected_choices = set(force_text(v) for v in selected_choices) output = [] output.append(format_html('<optgroup label="{}">', 'Global')) for option_value, option_label in self.choices: if not isinstance(option_label, (list, tuple)) and isinstance(option_label, basestring): output.append(self.render_option_value(selected_choices, option_value, option_label)) output.append('</optgroup>') for option_value, option_label in self.choices: if isinstance(option_label, (list, tuple)) and not isinstance(option_label, basestring): output.append(format_html('<optgroup label="{}">', force_text(option_value))) for option in option_label: if isinstance(option, (list, tuple)) and not isinstance(option, basestring): if isinstance(option[1][0], (list, tuple)) and not isinstance(option[1][0], basestring): for option_child in option[1][0]: output.append(self.render_option_value(selected_choices, *option_child, data_section=force_text(option[1][0][0]))) else: output.append(self.render_option_value(selected_choices, *option[1], data_section=force_text(option[0]))) else: output.append(self.render_option_value(selected_choices, *option, data_section=force_text(option_value))) output.append('</optgroup>') return '\n'.join(output)
def render(self): """ Outputs a grid for this set of choice fields. """ if len(self.choices) == 0: raise ValueError("Can't handle empty lists") variations = [] for key, value in self.choices: value['key'] = key variations.append(value) properties = [v.prop for v in variations[0].relevant_values()] dimension = len(properties) id_ = self.attrs.get('id', None) start_tag = format_html('<div class="variations" id="{0}">', id_) if id_ else '<div class="variations">' output = [start_tag] # TODO: This is very duplicate to pretixcontrol.views.item.ItemVariations.get_forms() # Find a common abstraction to avoid the repetition. if dimension == 0: output.append(format_html('<em>{0}</em>', _("not applicable"))) elif dimension == 1: output = self.render_1d(output, variations, properties) else: output = self.render_nd(output, variations, properties) output.append( ('<div class="help-block"><a href="#" class="variations-select-all">{0}</a> · ' '<a href="#" class="variations-select-none">{1}</a></div></div>').format( _("Select all"), _("Deselect all") ) ) return mark_safe('\n'.join(output))
def render(self): """ Outputs a <ul> for this set of choice fields. If an id was given to the field, it is applied to the <ul> (each item in the list will get an id of `$id_$i`). """ id_ = self.attrs.get('id', None) output = [] for i, choice in enumerate(self.choices): choice_value, choice_label = choice if isinstance(choice_label, (tuple, list)): attrs_plus = self.attrs.copy() if id_: attrs_plus['id'] += '_{}'.format(i) sub_ul_renderer = ChoiceFieldRenderer(name=self.name, value=self.value, attrs=attrs_plus, choices=choice_label) sub_ul_renderer.choice_input_class = self.choice_input_class output.append(format_html(self.inner_html, choice_value=choice_value, sub_widgets=sub_ul_renderer.render())) else: w = self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, i) output.append(format_html(self.inner_html, choice_value=force_text(w), sub_widgets='')) return format_html(self.outer_html, id_attr=format_html(' id="{}"', id_) if id_ else '', content=mark_safe('\n'.join(output)))
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = ['<div class="btn-group" data-toggle="buttons">'] # Normalize to strings str_values = set([force_text(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = format_html(' for="{0}"', final_attrs['id']) else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = force_text(option_label) output.append(format_html('<label class="btn btn-default btn-lg {0} {1}"{2}>{3} {4}</label>', 'active' if cb.check_test(option_value) else '', 'disabled' if 'disabled' in attrs else '', label_for, rendered_cb, option_label)) output.append('</div>') return mark_safe('\n'.join(output))
def __init__(self, name, value, attrs, choices): attrs.pop('djng-error', None) self.field_attrs = [format_html('ng-form="{0}"', name)] if attrs.pop('multiple_checkbox_required', False): field_names = [format_html('{0}.{1}', name, choice) for choice, dummy in choices] self.field_attrs.append(format_html('validate-multiple-fields="{0}"', json.dumps(field_names))) super(CheckboxFieldRendererMixin, self).__init__(name, value, attrs, choices)
def linked_page(self, obj): link = obj.link if link is not None: return format_html('<a href="{0}">{1}</a>', link, obj.page) else: return format_html('{0}', obj.page)
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, choices=()): to_opts = self.rel.to._meta if attrs is None: attrs = {} attrs['class'] = 'select2ajax' if self.multiple: attrs['multiple'] = 'multiple' attrs['data-search-url'] = self.admin_view.get_admin_url( '%s_%s_changelist' % (to_opts.app_label, to_opts.module_name)) attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name attrs['data-choices'] = '?' if self.rel.limit_choices_to: for i in list(self.rel.limit_choices_to): attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i]) attrs['data-choices'] = format_html(attrs['data-choices']) if value: attrs['data-label'] = self.label_for_value(value) if value is None: value = '' final_attrs = self.build_attrs(attrs, type='text', 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{0} />', flatatt(final_attrs))
def label_tag(self, contents=None, attrs=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. """ contents = contents or self.label # 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 self.form.label_suffix and contents and contents[-1] not in _(':?.!'): contents = format_html('{0}{1}', contents, self.form.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}) 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 format_callback(obj): p = '%s.%s' % ( obj._meta.app_label, get_permission_codename('delete', obj._meta) ) if not self.request.user.has_perm(p): perms_needed.add(obj._meta.verbose_name) registered = obj.__class__ in self.request.djangobmf_site.modules # only show bmf modules if not registered: return None if hasattr(obj, '_bmfmeta') and obj._bmfmeta.only_related: return format_html( '{0}: {1}', obj._meta.verbose_name, obj ) else: return format_html( '{0}: <a href="{1}">{2}</a>', obj._meta.verbose_name, obj.bmfmodule_detail(), obj )
def render(self): """ Outputs a <ul> for this set of choice fields. If an id was given to the field, it is applied to the <ul> (each item in the list will get an id of `$id_$i`). """ id_ = self.attrs.get('id', None) start_tag = format_html('<ul id="{0}">', id_) if id_ else '<ul>' output = [start_tag] for i, choice in enumerate(self.choices): choice_value, choice_label = choice if isinstance(choice_label, (tuple, list)): attrs_plus = self.attrs.copy() if id_: attrs_plus['id'] += '_{0}'.format(i) sub_ul_renderer = ChoiceFieldRenderer(name=self.name, value=self.value, attrs=attrs_plus, choices=choice_label) sub_ul_renderer.choice_input_class = self.choice_input_class output.append(format_html('<li>{0}{1}</li>', choice_value, sub_ul_renderer.render())) else: w = self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, i) output.append(format_html('<li>{0}</li>', force_text(w))) output.append('</ul>') return mark_safe('\n'.join(output))
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_option_value( self, selected_choices, option_value, option_label, data_section=None): if option_value is None: option_value = '' option_value = force_text(option_value) if option_value in selected_choices: selected_html = mark_safe(' selected') if not self.allow_multiple_selected: # Only allow for a single selection. selected_choices.remove(option_value) else: selected_html = '' label = force_text(option_label) if data_section is None: data_section = '' else: data_section = force_text(data_section) if '/' in data_section: label = format_html( '{} [{}]', label, data_section.rsplit( '/', 1)[1]) return format_html( '<option data-section="{}" value="{}"{}>{}</option>', data_section, option_value, selected_html, label)
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs inline = attrs and attrs.get('inline', False) final_attrs = self.build_attrs(attrs, name=name) output = [ ] str_values = set([force_text(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): if has_id: final_attrs = dict(final_attrs, id="%s_%s" % (attrs[id], i)) label_for = format_html(' for="{0}"', final_attrs['id']) else: label_for = '' if inline: label_class = "checkbox inline" else: label_class = "checkbox" label_class = format_html(' class="{0}"', label_class) cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = force_text(option_label) output.append(format_html('<label{0}{1}>{2} {3}</label>', label_for, label_class, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
def items_for_result(cl, result, form): """ Generates the actual list of data. @jjdelc: This has been shamelessly copied from original django.contrib.admin.templatetags.admin_list.items_for_result in order to alter the dispay for the first element """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: result_repr, row_class = get_result_and_row_class(cl, field_name, result) # If list_display_links not defined, add the link tag to the # first field if (first and not cl.list_display_links) or \ field_name in cl.list_display_links: table_tag = {True: 'th', False: 'td'}[first] # This spacer indents the nodes based on their depth spacer = get_spacer(first, result) # This shows a collapse or expand link for nodes with childs collapse = get_collapse(result) # Add a <td/> before the first col to show the drag handler drag_handler = get_drag_handler(first) first = False url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) onclickstr = format_html(""" onclick="opener.dismissRelatedLookupPopup(window, '{}'); return false;" """, mark_safe(value)) yield mark_safe( u('%s<%s%s>%s %s <a href="%s"%s>%s</a></%s>') % ( drag_handler, table_tag, row_class, spacer, collapse, url, (cl.is_popup and onclickstr or ''), conditional_escape(result_repr), table_tag)) else: # By default the fields come from ModelAdmin.list_editable, but if # we pull the fields out of the form instead of list_editable # custom admins can provide fields on a per request basis if ( form and field_name in form.fields and not ( field_name == cl.model._meta.pk.name and form[cl.model._meta.pk.name].is_hidden ) ): bf = form[field_name] result_repr = mark_safe(force_str(bf.errors) + force_str(bf)) yield format_html(u('<td{0}>{1}</td>'), row_class, result_repr) if form and not form[cl.model._meta.pk.name].is_hidden: yield format_html(u('<td>{0}</td>'), force_str(form[cl.model._meta.pk.name]))
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, name=name) content = self.render_options(choices, value) content = format_html(content) return mark_safe(format_html(self.outer_html, flatatt(final_attrs), content))
def paginator(items): if not items.paginator.num_pages > 1: return "" if items.has_previous(): prev_link = format_html(link_fmt, items.previous_page_number(), _("Previous")) else: prev_link = "" pages = _("Page %(page)d of %(page_count)d") % {"page": items.number, "page_count": items.paginator.num_pages} if items.has_next(): next_link = format_html(link_fmt, items.next_page_number(), _("Next")) else: next_link = "" return format_html( """<div class="row paginator"> <div class="col-sm-4">{}</div> <div class="col-sm-4 text-center">{}</div> <div class="col-sm-4 text-right">{}</div> </div>""", prev_link, pages, next_link, )
def as_ul(self): if not self: return SafeText() first = self[0] if isinstance(first, tuple): valid_list = [] invalid_list = [] for e in self: """ Ignore $pristine errors, as they relate to the original rejected error handling or djng-error bound-field""" if e[2] == '$pristine': continue if e[3] == '$valid': li_format = self.li_format_valid error_list = valid_list elif e[5] == '$message': li_format = self.li_format_bind error_list = invalid_list else: li_format = self.li_format error_list = invalid_list msg_type = e[3].split('.') err_tuple = (e[0], msg_type[0] if len(msg_type) == 1 else msg_type.pop(), e[4], force_text(e[5])) error_list.append(format_html(li_format, *err_tuple)) return mark_safe(format_html(self.ul_format_valid, first[0], first[1], self._get_form_name(first[0]), mark_safe(''.join(valid_list)))) \ + mark_safe(format_html(self.ul_format, first[0], first[1], self._get_form_name(first[0]), mark_safe(''.join(invalid_list)))) return format_html('<ul class="errorlist">{0}</ul>', format_html_join('', '<li>{0}</li>', ((force_text(e),) for e in self)))
def render_options(self, choices, selected_choices): output = [] for option_value, option_label in chain(self.choices, choices): if option_value in selected_choices: value = format_html(' value={}', option_value) output.append(format_html(self.inner_html, value, label=force_unicode(option_label))) return '\n'.join(output)
def render(self, name=None, value=None, attrs=None, choices=()): if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else self.attrs help_text = """\ <a href="#" data-toggle="modal" data-target="#geodata-modal-techniques-%(pk)s"> <span class="glyphicon glyphicon-question-sign"></span> </a> <div class="modal fade" id="geodata-modal-techniques-%(pk)s"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title">%(name)s</h4> </div> <div class="modal-body"> %(description)s</br> <a href="%(url)s">%(url)s</a> </div> </div> </div> </div> """ % {'name': self.choice_obj.name, 'url': self.choice_obj.url, 'pk': self.choice_obj.pk, 'description': self.choice_obj.description} return format_html( '<label{}>{} {}</label>{}', label_for, self.tag(attrs), self.choice_label, mark_safe(help_text) )
def friendly_status(self, host_maintenance): html_success = '<span class="label label-info">Success</span>' html_rejected = '<span class="label label-important">{}</span>' html_waiting = '<span class="label label-warning">Waiting</span>' html_running = '<span class="label label-success">Running</span>' html_revoked = '<span class="label label-primary">{}</span>' if host_maintenance.status == models.HostMaintenance.SUCCESS: return format_html(html_success) elif host_maintenance.status == models.HostMaintenance.ERROR: return format_html(html_rejected.format("Error")) elif host_maintenance.status == models.HostMaintenance.ROLLBACK: return format_html(html_rejected.format("Rollback")) elif host_maintenance.status == models.HostMaintenance.ROLLBACK_ERROR: return format_html(html_rejected.format("Rollback Error")) elif host_maintenance.status == models.HostMaintenance.ROLLBACK_SUCCESS: return format_html(html_rejected.format("Rollback Succes")) elif host_maintenance.status == models.HostMaintenance.WAITING: return format_html(html_waiting) elif host_maintenance.status == models.HostMaintenance.RUNNING: return format_html(html_running) elif host_maintenance.status == models.HostMaintenance.REVOKED: return format_html(html_revoked.format("Revoked")) elif host_maintenance.status == models.HostMaintenance.UNAVAILABLEHOST: return format_html(html_revoked.format("Unavailable Host")) elif host_maintenance.status == models.HostMaintenance.UNAVAILABLECSHOSTATTR: return format_html(html_revoked.format("Unavailable CsHost"))
def render(self, name=None, value=None, attrs=None, choices=()): if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = "" attrs = dict(self.attrs, **attrs) if attrs else self.attrs return format_html("<label{}>{} {}</label>", label_for, self.tag(attrs), self.choice_label)
def get_tree(data_file): with open(data_file, 'rb') as fp: try: tree = etree.parse(fp) except lxml.etree.XMLSyntaxError as err: raise CoveInputDataError(context={ 'sub_title': _("Sorry, we can't process that data"), 'link': 'index', 'link_text': _('Try Again'), 'msg': _(format_html('We think you tried to upload a XML file, but it is not well formed XML.' '\n\n<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true">' '</span> <strong>Error message:</strong> {}', err)), 'error': format(err) }) except UnicodeDecodeError as err: raise CoveInputDataError(context={ 'sub_title': _("Sorry, we can't process that data"), 'link': 'index', 'link_text': _('Try Again'), 'msg': _(format_html('We think you tried to upload a XML file, but the encoding is incorrect.' '\n\n<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true">' '</span> <strong>Error message:</strong> {}', err)), 'error': format(err) }) return tree
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = ['<ul>'] long_val = to_long(value) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if to_long(option_value) == 0: continue if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = format_html(' for="{0}"', final_attrs['id']) else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: bool(to_long(value) & long_val)) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = force_text(option_label) output.append(format_html('<li><label{0}>{1} {2}</label></li>', label_for, rendered_cb, option_label)) output.append('</ul>') return mark_safe('\n'.join(output))
def render(self, name, value, attrs=None, renderer=None): html = super(TextInputWithButtons, self).render(name, value, attrs, renderer) from django.utils.html import format_html, mark_safe, escapejs id = attrs["id"] def make_feedback_func(feedback): return "'$(\"#{id}\").val(\"{feedback}\")'".format( id=id, feedback=escapejs(feedback)) buttons = [] # Add buttons. for button_value in self.button_values: buttons.append(format_html( "<button class='btn btn-xs btn-default' " "type='button' onclick={func}>{val}</button>", func=mark_safe(make_feedback_func(button_value)), val=button_value)) # Add a clear button. buttons.append(format_html( "<button class='btn btn-xs btn-default' " "type='button' onclick={func}>Clear</button>", func=mark_safe(make_feedback_func("")))) return format_html("{html}<p>{button_row}</p>", html=html, button_row=mark_safe("".join(buttons)))
def format(obj, account=False): has_admin = obj.__class__ in admin_site._registry opts = obj._meta no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), force_text(obj)) if has_admin: try: admin_url = reverse('admin:%s_%s_change' % (opts.app_label, opts.model_name), None, (quote(obj._get_pk_val()),) ) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit return no_edit_link p = '%s.%s' % (opts.app_label, get_permission_codename('delete', opts)) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. context = (capfirst(opts.verbose_name), admin_url, obj) if account: context += (_("services to delete:"),) return format_html('{} <a href="{}">{}</a> {}', *context) return format_html('{}: <a href="{}">{}</a>', *context) else: # Don't display link to edit, because it either has no # admin or is edited inline. return no_edit_link
def status_flag(self): if self.status == "CL": return format_html("<span style='color : red;'>✖</span>") if self.status == "PD": return format_html("<span style='color : green;'>✔</span>") return format_html("<span style='color : black;'>⛔</span>")
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = ['<div class="btn-group" data-toggle="buttons">'] # Normalize to strings str_values = set([force_text(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = format_html(' for="{0}"', final_attrs['id']) else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = force_text(option_label) option_labels = option_label.split('|#~|') output.append(format_html('<label class="choice btn btn-default btn-lg {0} {1}"{2}>{3} <img class="img-thumbnail tooltip_link" src="{4}{5}" style="width:100px" title="{6}" alt="{6}"/><span class="price">{7}</span></label>', 'active' if cb.check_test(option_value) else '', 'disabled' if 'disabled' in attrs else '', label_for, rendered_cb, settings.MEDIA_URL, option_labels[1], option_labels[0], option_labels[2])) output.append('</div>') return mark_safe('\n'.join(output))
def login_user(request): # prevent a logged in user from accessing the login page if(request.user.pk): return HttpResponseRedirect(reverse('app_book:archivesPage')) form = AuthenticationForm if request.method == "POST": email = request.POST['username'] password = request.POST['password'] user = authenticate(email=email, password=password) if user is not None: if user.is_active: if User.objects.filter(pk=user.id).first().emailConfirm == 1: login(request, user) # Redirect to a success page. elif settings.DEBUG: messages.add_message(request, messages.INFO, format_html("Die E-Mail-Adresse wurde noch nicht bestätigt. Debugmodus aktiv, Login gestattet. <a href='{}'>Aktivierungslink erneut zusenden</a>", reverse('app_user:resend_confirmation_mail', kwargs={'email': email}))) login(request, user) else: messages.add_message(request, messages.ERROR, format_html("Die E-Mail-Adresse wurde noch nicht bestätigt. <a href='{}'>Aktivierungslink erneut zusenden</a>", reverse('app_user:resend_confirmation_mail', kwargs={'email': email}))) else: # Return a 'disabled account' error message messages.add_message(request, messages.ERROR, 'Das Benutzerkonto ist deaktiviert.') if not 'next' in request.POST: return HttpResponseRedirect(reverse('app_book:archivesPage')) else: return HttpResponseRedirect(request.POST['next']) else: # Return an 'invalid login' error message. messages.add_message(request, messages.ERROR, 'Loginversuch fehlgeschlagen.') return render_to_response('registration/login.html', {'form': form}, RequestContext(request)) else: return render_to_response('registration/login.html', {'form': form, 'next': request.GET.get('next') or ''}, RequestContext(request))
def get_content_title(self): if self.problem.is_accessible_by(self.request.user): return format_html(_('Best solutions for <a href="{1}">{0}</a> in <a href="{3}">{2}</a>'), self.problem_name, reverse('problem_detail', args=[self.problem.code]), self.contest.name, reverse('contest_view', args=[self.contest.key])) return format_html(_('Best solutions for problem {0} in <a href="{2}">{1}</a>'), self.get_problem_number(self.problem), self.contest.name, reverse('contest_view', args=[self.contest.key]))
def items_for_result(cl, result, form): """ Generate the actual list of data. """ def link_in_col(is_first, field_name, cl): if cl.list_display_links is None: return False if is_first and not cl.list_display_links: return True return field_name in cl.list_display_links first = True pk = cl.lookup_opts.pk.attname for field_index, field_name in enumerate(cl.list_display): empty_value_display = cl.model_admin.get_empty_value_display() row_classes = ['field-%s' % _coerce_field_name(field_name, field_index)] try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except ObjectDoesNotExist: result_repr = empty_value_display else: empty_value_display = getattr(attr, 'empty_value_display', empty_value_display) if f is None or f.auto_created: if field_name == 'action_checkbox': row_classes = ['action-checkbox'] boolean = getattr(attr, 'boolean', False) result_repr = display_for_value(value, empty_value_display, boolean) if isinstance(value, (datetime.date, datetime.time)): row_classes.append('nowrap') else: if isinstance(f.remote_field, models.ManyToOneRel): field_val = getattr(result, f.name) if field_val is None: result_repr = empty_value_display else: result_repr = field_val else: result_repr = display_for_field(value, f, empty_value_display) if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)): row_classes.append('nowrap') if str(result_repr) == '': result_repr = mark_safe(' ') row_class = mark_safe(' class="%s"' % ' '.join(row_classes)) # If list_display_links not defined, add the link tag to the first field if link_in_col(first, field_name, cl): table_tag = 'th' if first else 'td' first = False # Display link to the result's change_view if the url exists, else # display just the result's representation. try: url = cl.url_for_result(result) except NoReverseMatch: link_or_text = result_repr else: url = add_preserved_filters({'preserved_filters': cl.preserved_filters, 'opts': cl.opts}, url) # Convert the pk to something that can be used in Javascript. # Problem cases are non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) link_or_text = format_html( '<a href="{}"{}>{}</a>', url, format_html( ' data-popup-opener="{}"', value ) if cl.is_popup else '', result_repr) yield format_html('<{}{}>{}</{}>', table_tag, row_class, link_or_text, table_tag) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if (form and field_name in form.fields and not ( field_name == cl.model._meta.pk.name and form[cl.model._meta.pk.name].is_hidden)): bf = form[field_name] result_repr = mark_safe(str(bf.errors) + str(bf)) yield format_html('<td{}>{}</td>', row_class, result_repr) if form and not form[cl.model._meta.pk.name].is_hidden: yield format_html('<td>{}</td>', form[cl.model._meta.pk.name])
def myphoto(self, object): return format_html('<img src={} width="40"/>'.format(object.photo.url))
def display_link(self, object): return format_html('<a target="_blank" href="{0}">{0}</a>', object.link)
def render_id(self, value): return format_html('<input type="hidden" name="id" value="{}" />', str(value))
def render(self,value): if value: return format_html("<i class=\"fas fa-check\" style=\"color:green;\"></i>") else: return format_html("<i class=\"fas fa-times\" style=\"color:red;\"></i>")
def rendered(self): for x in self.data: yield format_html(self.string_template, force_text(x))
def custom_column(self, obj): return format_html('<div class="custom" id="test-' + str(obj.pk) + '">' + str(obj.pk) + '</dev>')
def result_headers(cl): """ Generate the list column headers. """ ordering_field_columns = cl.get_ordering_field_columns() for i, field_name in enumerate(cl.list_display): text, attr = label_for_field( field_name, cl.model, model_admin=cl.model_admin, return_attr=True ) is_field_sortable = cl.sortable_by is None or field_name in cl.sortable_by if attr: field_name = _coerce_field_name(field_name, i) # Potentially not sortable # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield { "text": text, "class_attrib": mark_safe(' class="action-checkbox-column"'), "sortable": False, } continue admin_order_field = getattr(attr, "admin_order_field", None) # Set ordering for attr that is a property, if defined. if isinstance(attr, property) and hasattr(attr, 'fget'): admin_order_field = getattr(attr.fget, 'admin_order_field', None) if not admin_order_field: is_field_sortable = False if not is_field_sortable: # Not sortable yield { 'text': text, 'class_attrib': format_html(' class="column-{}"', field_name), 'sortable': False, } continue # OK, it is sortable if we got this far th_classes = ['sortable', 'column-{}'.format(field_name)] order_type = '' new_order_type = 'asc' sort_priority = 0 # Is it currently being sorted on? is_sorted = i in ordering_field_columns if is_sorted: order_type = ordering_field_columns.get(i).lower() sort_priority = list(ordering_field_columns).index(i) + 1 th_classes.append('sorted %sending' % order_type) new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type] # build new ordering param o_list_primary = [] # URL for making this field the primary sort o_list_remove = [] # URL for removing this field from sort o_list_toggle = [] # URL for toggling order type for this field def make_qs_param(t, n): return ('-' if t == 'desc' else '') + str(n) for j, ot in ordering_field_columns.items(): if j == i: # Same column param = make_qs_param(new_order_type, j) # We want clicking on this header to bring the ordering to the # front o_list_primary.insert(0, param) o_list_toggle.append(param) # o_list_remove - omit else: param = make_qs_param(ot, j) o_list_primary.append(param) o_list_toggle.append(param) o_list_remove.append(param) if i not in ordering_field_columns: o_list_primary.insert(0, make_qs_param(new_order_type, i)) yield { "text": text, "sortable": True, "sorted": is_sorted, "ascending": order_type == "asc", "sort_priority": sort_priority, "url_primary": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}), "url_remove": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}), "url_toggle": cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), "class_attrib": format_html(' class="{}"', ' '.join(th_classes)) if th_classes else '', }
def operator(self,obj): return format_html( '<a href="{}">编辑</a>', reverse('xadmin:blog_post_change',args=(obj.id,)) )
def _boolean_icon(field_val): icon_url = static('admin/img_manual/icon-%s.svg' % {True: 'yes', False: 'no', None: 'unknown'}[field_val]) return format_html('<img_manual src="{}" alt="{}">', icon_url, field_val)
def photo_img(self, obj): return format_html('<img width="32px" src="{0}" />', obj.photo)
def get_simple_stats(): today = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) credited_stats = Credit.objects.credited() \ .aggregate(count=models.Count('*'), amount=models.Sum('amount')) credited_stats['amount'] = credited_stats['amount'] or 0 pending_credits = Credit.objects.credit_pending() \ .filter(received_at__lt=today) \ .count() digital_takeup = DigitalTakeup.objects.mean_digital_takeup() credit_stats = [ { 'title': _('Credited'), 'value': format_html( '{}<br>{}', ngettext('%(number)s credit', '%(number)s credits', credited_stats['count']) % { 'number': format_number(credited_stats['count'], truncate_after=1000000) }, format_amount(credited_stats['amount'], trim_empty_pence=True), ), }, { 'title': _('Pending'), 'value': ngettext('%(number)s credit', '%(number)s credits', pending_credits) % { 'number': format_number(pending_credits, truncate_after=1000000) }, }, { 'title': _('Digital take-up'), 'value': '?' if digital_takeup is None else format_percentage(digital_takeup), }, ] sent_stats = Disbursement.objects.sent() \ .aggregate(count=models.Count('*'), amount=models.Sum('amount')) sent_stats['amount'] = sent_stats['amount'] or 0 pending_disbursements = Disbursement.objects \ .exclude(resolution=DISBURSEMENT_RESOLUTION.REJECTED) \ .exclude(resolution=DISBURSEMENT_RESOLUTION.SENT) \ .count() disbursement_stats = [ { 'title': _('Sent'), 'value': format_html( '{}<br>{}', ngettext('%(number)s disbursement', '%(number)s disbursements', sent_stats['count']) % { 'number': format_number(sent_stats['count'], truncate_after=1000000) }, format_amount(sent_stats['amount'], trim_empty_pence=True), ), }, { 'title': _('Pending'), 'value': ngettext('%(number)s disbursement', '%(number)s disbursements', pending_disbursements) % { 'number': format_number(pending_disbursements, truncate_after=1000000) }, }, ] try: earliest_credit = Credit.objects.earliest() except Credit.DoesNotExist: earliest_credit = None try: earliest_disbursement = Disbursement.objects.earliest() except Disbursement.DoesNotExist: earliest_disbursement = None return { 'credits': credit_stats, 'earliest_credit': earliest_credit, 'disbursements': disbursement_stats, 'earliest_disbursement': earliest_disbursement, }
def formatted_results(self, obj): return format_html('<pre>{}</pre>', json.dumps(obj.results, indent=2))
def __html__(self): return format_html( '{}"{}', static(self.js), mark_safe(flatatt(self.attrs)), ).rstrip('"')
def attachment_url(self, obj): attachment = obj.attachment url = reverse("admin:attachments_attachment_change", args=(attachment.pk, )) return format_html('<a href="{}">{}</a>', url, attachment.pk)
def website_link(self, obj): return format_html('<a href="{0}">{0}</a>', obj.website)
def album_preview(self, obj): """Format album photo preview""" print(obj) return format_html( '<img src="/media/{}" style="width: 130px; height: auto"/>'.format( obj.preview.src))
def full_url(self, obj): url = obj.get_file_url() return format_html( '<a href="{}" target="_blank" rel="noopener">{}</a>', url, url)
def render_basic(self, value, context=None): if value: return format_html('<a href="{0}">{1}</a>', value.url, value.title) else: return ""
def info_row(header, item, postfix=u'', prefix=u''): result = u'' if item: result = format_html(u'<tr><th>{}</th><td>{}{}{}</td></tr>', header, prefix, item, postfix) return result
def import_wagtailfontawesome_stylesheet(): return format_html('<link rel="stylesheet" href="{}">', static('wagtailfontawesome/css/wagtailfontawesome.css'))
def article_tags(self, obj): tags = '' for each in obj.tags.all(): tags += each.name + "/" return format_html("%s" % tags)
def harvest_job_actions(self, obj): url = furl(reverse('admin:source-config-harvest', args=[obj.source_config_id])) url.args['start'] = self.start_date_(obj) url.args['end'] = self.end_date_(obj) url.args['superfluous'] = True return format_html('<a class="button" href="{}">Restart</a>', url.url)
def render_basic(self, value, context=None): if value: return format_html("<blockquote>{0}</blockquote>", value) else: return ""
def readonly_link(obj, display_str=None): url = reverse('admin:{}_{}_change'.format(obj._meta.app_label, obj._meta.model_name), args=[obj.id]) return format_html('<a href="{}">{}</a>', url, display_str or str(obj))
def html_parent_page_title(self): return format_html( '<a href="/admin/pages/{}/edit/">{}</span>', self.get_parent().id, self.get_parent().title )
def render(self): inner = format_html_join("\n", '<li style="white-space: nowrap">{0}</li>', zip(self)) return format_html('<ul class="radio-select">\n{0}\n</ul>', inner)
def status_(self, obj): return format_html( '<span style="font-weight: bold; color: {}">{}</span>', STATUS_COLORS[obj.status], AbstractBaseJob.STATUS[obj.status].title(), )
def has_profile_photo(self, obj): return obj.profile_photo and format_html('<h1>🗿</h1>') or ''
def image_to_html(self, image, alt_text, extra_attributes=None): default_html = super().image_to_html(image, alt_text, extra_attributes) return format_html("{}<figcaption>{}</figcaption>", default_html, alt_text)