自定义小部件未标记为安全

时间:2016-05-05 15:04:01

标签: django django-forms

我正在创建一个自定义小部件,将选项字段显示为一行按钮。

到目前为止,我已经从Django源代码中复制了代码,用于渲染无线电选择字段作为我的起点:

@html_safe
@python_2_unicode_compatible
class ButtonInput(SubWidget):

  input_type = 'radio'

  def __init__(self, name, value, attrs, choice, index):
    self.name = name
    self.value = value
    self.attrs = attrs
    self.choice_value = force_text(choice[0])
    self.choice_label = force_text(choice[1])
    self.index = index
    if 'id' in self.attrs:
        self.attrs['id'] += "_%d" % self.index
    self.value = force_text(self.value)

  def __str__(self):
      return self.render()

  def render(self, name=None, value=None, attrs=None):
      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 is_checked(self):
      return self.value == self.choice_value

  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))

  @property
  def id_for_label(self):
      return self.attrs.get('id', '')


class ButtonFieldRenderer(ChoiceFieldRenderer):
    choice_input_class = ButtonInput


class ButtonSelect(RendererMixin, Select):
    renderer = ButtonFieldRenderer
    _empty_value = ''

我的问题是这段代码呈现了正确的HTML,但它没有标记为安全 - HTML代码呈现在页面上。鉴于此代码基本上是直接从Django源代码复制的,这是非常令人惊讶的。

缺少什么?如何使我的widget类html安全?

1 个答案:

答案 0 :(得分:2)

更改u&#39;&#39;的渲染方法中的字符串为我工作

  def render(self, name=None, value=None, attrs=None):
      if self.id_for_label:
          label_for = format_html(u' for="{}"', self.id_for_label)
      else:
          label_for = ''
      attrs = dict(self.attrs, **attrs) if attrs else self.attrs
      return format_html(
          u'<label{}>{} {}</label>', label_for, self.tag(attrs), self.choice_label
      )