Reputation: 1499
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'??
Upvotes: 1
Views: 1528
Reputation: 2289
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 ;)
Upvotes: 1