强制使用“filter_horizo​​ntal”用于重新定义的模型字段

发布于 2024-10-18 14:49:37 字数 1937 浏览 0 评论 0原文

我有一个模型字段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_horizo​​ntal小部件管理员。似乎它仅与 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_horizo​​ntal 用于在“forms”中重新定义的 dbfield m2m 字段?

I have a model field users, but have modified its output, effectively overriding unicode :

from django import forms

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

and...

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',
                })
        })

but I still lose the filter_horizontal widget in the admin. It seems that its inextricably tied to model/dbfields only... I've identified this area in django.contrib.admin.options.py (line 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))

So, how to 'force' use of the filter_horizontal for dbfield m2m fields that are redefined in `forms'??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想你的星星会说话 2024-10-25 14:49:37

如果您使用普通的 ModelMultipleChoiceField,则可以在 ArticleAdminModelForm 内的用户定义中定义小部件。当对字段进行子类化时,Python默认情况下不会调用其超类的 init 方法(但可能背后有一些 django 魔法),因此您可能需要自己实现 init 方法正如文档中所述。

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

尚未测试这是否有效;)

Defining the widget inside the user definition inside ArticleAdminModelForm would be the way to do it if you were using the normal ModelMultipleChoiceField. When subclassing a field, python by default does not call its superclass init method (but maybe there is some django magic behind), so you might need to implement the init method yourself as it says in the docs.

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

haven't tested if this works ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文