2013-10-13 30 views

回答

5

你继承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 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) 
+0

使用正常的ModelChoiceField,Django 1.7没有开箱工作。我必须重写label_from_instance方法,如下所示: 'def label_from_instance(self,obj): return obj' – baxeico

+0

这对于这样简单的任务来说很复杂。 Django必须为此做点事情。 –

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 
+0

但是如果我w ant是一个动态数据属性。像在管理中的下拉列表项目?谢谢 –

相关问题