如何在Django表单小部件中添加额外的上下文信息

3
基本的Django复选框多选小部件可以通过传递
3个回答

1
这可能不是最佳解决方案,但它可行。
我像这样重写 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 }}获取这些属性。


1
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 }}访问


0
如果您有一个包含ForeignKey(ModelChoiceField)的ModelForm,您可以在自定义小部件中设置其他上下文,如下所示:
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 }}

这样可以避免再次访问数据库以添加模型中的更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接