我正在創建自定義小部件,以將選擇字段顯示爲一排按鈕。未標記爲安全的自定義小部件
到目前爲止,我已經複製從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安全?
是否使用的是Django的版本的工作?你是否從適當的版本複製了代碼? – Alasdair
@Alasdair 1.9,我已經檢查過,沒有任何區別 – fredley
嘗試在'ButtonFieldRenderer'類中使用'@ html_safe'裝飾器。 – Alasdair