日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2025/3/12 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)

總結

以上是生活随笔為你收集整理的django 表单html5,我们如何在django管理表单中添加动态html5数据属性的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。