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

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

我只是找到了一个自定义的SelectWidget的实施OpenStack's dashboard:

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_value

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'%s' % (

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值