基本的Django复选框多选小部件可以通过传递
create_option
:def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
ctx = super().create_option(name, value, label, selected, index, subindex=subindex, attrs=attrs)
obj = AddOnItem.objects.get(id=int(value))
ctx['icon'] = obj.icon
ctx['description'] = obj.description
ctx['price'] = obj.price
return ctx
然后我可以在模板中使用{{ widget.field_name }}
获取这些属性。
MultiWidget
的情况下,类似于@HenryM的回答,可以子类化get_context
方法并像这样分配值:def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
context["some_field"] = "some_value"
return context
在模板中可以通过{{ some_field }}
访问
class CustomRadioSelect(forms.RadioSelect):
option_template_name = "widgets/test.html"
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
for option in context['widget']['optgroups']:
_, opts, _ = option
for opt in opts:
opt['other_attributes'] = opt['value'].instance.other_attributes
return context
other_attributes
,我想在我的小部件中访问它。option_template
中:{{ widget.other_attributes }}
这样可以避免再次访问数据库以添加模型中的更多信息。