如果您需要進一步自定義輸入元素,請覆蓋自定義渲染器上的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源代碼,改性僅略微顯示中的每一個簡單的定製的應用程序。