似乎很少有人使用它,但是...我做到了。在这里您可以阅读:
删除了django.forms.widgets中一些未记录的类:SubWidget RendererMixin,ChoiceFieldRenderer,RadioFieldRenderer,CheckboxFieldRenderer ChoiceInput,RadioChoiceInput,CheckboxChoiceInput
我的源代码是:
from django.forms.widgets import ChoiceFieldRenderer, RadioChoiceInput, \
RendererMixin, Select
class BootstrapRadioFieldRenderer(ChoiceFieldRenderer):
outer_html = '<span {id_attr}>{content}</span>'
inner_html = '<div class="radio">{choice_value}{sub_widgets}</div>'
choice_input_class = RadioChoiceInput
class BootstrapRadioSelect(RendererMixin, Select):
renderer = BootstrapRadioFieldRenderer
_empty_value = ''
Run Code Online (Sandbox Code Playgroud)
我真的不知道如何将其转换为与1.11及更高版本兼容:他们说:
Use a custom widget template instead.
Run Code Online (Sandbox Code Playgroud)
好。怎么样?
我们使用 RadioFieldRenderer 为每个选项添加描述。您的用例可能与此相去甚远,但我希望它也能帮助您进行迁移。
这是 Django <=1.10 的遗留代码
class MyRadioFieldRenderer(forms.widgets.RadioFieldRenderer):
def render(self):
radios = []
for w in self:
radios.append(u"""<li class="%s">%s <span>%s</span></li>"""
% (w.choice_value, force_unicode(w), get_description(w)))
return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join(radios))
class MyRadioSelect(forms.RadioSelect):
renderer = MyRadioFieldRenderer
Run Code Online (Sandbox Code Playgroud)
我将其替换为 Django 1.11,利用自定义模板片段,仅将描述添加到模板上下文中。
from django.forms.widgets import RadioSelect
class MyRadioSelect(RadioSelect):
template_name = 'myapp/multiple_input.html'
option_template_name = 'myapp/input_option.html'
def get_context(self, name, value, attrs):
context = super(MyRadioSelect, self).get_context(name, value, attrs)
for i in range(len(context['widget']['optgroups'][0][1])):
value = context['widget']['optgroups'][0][1][i]['value']
context['widget']['optgroups'][0][1][i]['attrs']['description'] = \
get_description(value)
return context
Run Code Online (Sandbox Code Playgroud)
这个深层列表中的 for 循环并不漂亮。需要再看一下。
在模板片段中,我可以使用以下命令呈现选项后面的描述<span>{{widget.attrs.description | safe}}</span>
形式保持不变:
class MyForm(forms.Form):
order_method = ChoiceField(
widget=MyRadioSelect,
required=True)
Run Code Online (Sandbox Code Playgroud)
重要提示:为了让 Django 在常规模板文件夹中找到自定义模板片段,请将其添加到您的设置中:
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
Run Code Online (Sandbox Code Playgroud)
和django.forms你的INSTALLED_APPS
| 归档时间: |
|
| 查看次数: |
685 次 |
| 最近记录: |