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

标签 django django-admin

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

例如

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

谢谢,

凯尔

最佳答案

您需要子类化 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)

关于django - 我们如何在 django 管理表单中添加动态 html5 数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19343575/

相关文章:

django - 通过主管监督 virtualenv django 应用程序

Python - Django - 将参数传递给 Form Clean 方法

python - 从 Django 调用 Postgres SQL 存储过程

python - Django:在管理界面中伪造一个字段?

django - 如何仅为 django 管理门户设置默认 TZ?

python - 在 django admin 中呈现时强制转换为 Unicode : need string or buffer, NoneType

django - 我们如何为 Django 表单中的浮点字段提供占位符?

Django - 在模型方法中将模型字段设置为 DB "Now"值

python - Django 1.8 admin,弹出窗口保存后显示空白页面

mysql - 保存/更新模型时 Django "Lock wait timeout exceeded; try restarting transaction"