如果您需要进一步自定义输入元素,请覆盖自定义渲染器上的choice_input_class 属性。
from django.forms.widgets import RadioChoiceInput, RadioFieldRenderer
from django.utils.safestring import mark_safe
from django.utils.html import format_html
class MyCustomRenderer( RadioFieldRenderer ):
choice_input_class = MyCustomInputClass
class MyCustomInputClass(RadioChoiceInput):
def render(self, name=None, value=None, attrs=None, choices=()):
# Generate outer label, insert a custom div
output = format_html('''
<div id="{}"></div>
''', self.choice_label)
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), output)
def tag(self, attrs=None):
# Generate the customized input element.
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{} class="my_custom_class" />', flatatt(final_attrs))
这些render()
和tag()
方法均来自 1.9 的源代码,仅稍作修改以显示在每个应用程序中的简单定制。