我们如何在django管理表单中添加动态html5数据属性

时间:2013-10-13 09:15:34

标签: django django-admin

我只想问一下如何在django管理表单中的每个fiels中添加额外的动态html5数据属性。

例如

    <option value ="1" data-desc="desc1">hello1</option>
    <option value ="2" data-desc="desc2">hello2</option>

谢谢,

凯尔

2 个答案:

答案 0 :(得分:5)

您需要继承Django的ModelChoiceField并修改它的render_options()render_option()方法,以显示您需要的对象属性。我猜你还需要你自己的ModelChoiceIterator子类,这样它不仅可以输出id / label元组,而且还可以输出你需要的所有数据。

实施例

我刚刚在OpenStack's dashboard中找到了自定义SelectWidget的实现:

class SelectWidget(widgets.Select):
    """
    Customizable select widget, that allows to render
    data-xxx attributes from choices.

    .. attribute:: data_attrs

        Specifies object properties to serialize as
        data-xxx attribute. If passed ('id', ),
        this will be rendered as:
        <option data-id="123">option_value</option>
        where 123 is the value of choice_value.id

    .. attribute:: transform

        A callable used to render the display value
        from the option object.
    """

    def __init__(self, attrs=None, choices=(), data_attrs=(), transform=None):
        self.data_attrs = data_attrs
        self.transform = transform
        super(SelectWidget, self).__init__(attrs, choices)

    def render_option(self, selected_choices, option_value, option_label):
        option_value = force_unicode(option_value)
        other_html = (option_value in selected_choices) and \
                         u' selected="selected"' or ''
        if not isinstance(option_label, (basestring, Promise)):
            for data_attr in self.data_attrs:
                data_value = html.conditional_escape(
                    force_unicode(getattr(option_label,
                                          data_attr, "")))
                other_html += ' data-%s="%s"' % (data_attr, data_value)

            if self.transform:
                option_label = self.transform(option_label)
        return u'<option value="%s"%s>%s</option>' % (
            html.escape(option_value), other_html,
            html.conditional_escape(force_unicode(option_label)))

修改

只要你提供这样的选择,就应该有效:

def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'dummy':
            widget = SelectWidget(data_attrs=('bar',))
            choices = [(foo.id, foo) for foo in Foo.objects.all()]
            form_field = forms.ChoiceField(
                choices=choices, widget=widget)
            return form_field
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

答案 1 :(得分:3)

您可以使用get_form()方法调整ModelAdmin使用的表单。

通过这种方式,您可以更改相关字段的小部件:

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
        form.fields['your_field'].widget.attrs.update({'data-hello': 'world'})
        return form