强制使用'filter_horizo​​ntal'来重新定义模型字段

时间:2011-02-21 23:53:12

标签: django django-models django-admin django-forms

我有一个模型字段users,但已修改其输出,有效地覆盖 unicode

from django import forms

class UserModelMultipleChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s, %s" % (obj.last_name, obj.first_name)

和...

from django.contrib.admin.widgets import FilteredSelectMultiple

class ArticleAdminModelForm(BaseAdminModelForm):

    users = UserModelMultipleChoiceField(
        queryset = User.objects.order_by('last_name', 'first_name'))

    class Meta:
        model = get_model('articles', 'article')
        widgets = BaseAdminModelForm.Meta.widgets

        # Trying to force filter_horizontal -- but to no avail.
        widgets = {
            'users': FilteredSelectMultiple(
                verbose_name="users",
                is_stacked=True,
                attrs={
                    'class': 'filtered',
                })
        })

但我仍然丢失了管理员中的filter_horizontal小部件。它似乎只与model / dbfields密不可分......我在django.contrib.admin.options.py(第157行)中确定了这个区域

def formfield_for_manytomany(self, db_field, request=None, **kwargs):
    """
    Get a form Field for a ManyToManyField.
    """
    # If it uses an intermediary model that isn't auto created, don't show
    # a field in admin.
    if not db_field.rel.through._meta.auto_created:
        return None
    db = kwargs.get('using')

    if db_field.name in self.raw_id_fields:
        kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)
        kwargs['help_text'] = ''
    elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
        kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))

那么,如何'强制'使用filter_horizontal用于在`forms'中重新定义的dbfield m2m字段?

1 个答案:

答案 0 :(得分:1)

如果使用普通的ModelMultipleChoiceField,在ArticleAdminModelForm中定义用户定义中的窗口小部件将是这样做的方法。子类化字段时,默认情况下python不会调用其超类 init 方法(但可能会有一些django魔法),因此您可能需要自己实现 init 方法正如它在docs中所说的那样。

users = forms.ModelMultipleChoiceField(
        widget=FilteredSelectMultiple(
                                      verbose_name='aktive_mitarbeiter',
                                      is_stacked=False
                                     )
        queryset=User.objects.filter(is_active=True)
        )

尚未测试是否有效;)