Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: AJAX ManyToManyField in admin
    primarykey
    data
    text
    <p>I want to display <code>ManyToManyField</code>s in admin just like <code>filter_horizontal</code> does, but populate the options as the user types into the filter field. There are many options and loading them all at once takes a lot of time. </p> <p>I found <a href="http://code.google.com/p/django-ajax-filtered-fields/" rel="noreferrer">django-ajax-filtered-fields</a> but it seems to me an overkill as it requires changes to model classes, when all I want to do is to replace every multiple select field in a form.</p> <p>Writing a custom widget field that inherits from <code>admin.widgets.FilteredSelectMultiple</code> seems to be the right way. So I am trying to roll my own widget:</p> <pre><code>class MultiSelectWidget(FilteredSelectMultiple): class Media: # here should be some js to load options dynamically js = ( "some_js_to_load_ajax_options.js", ) def render_options(self, choices, selected_choices): # this initializes the multiple select without any options choices = [c for c in self.choices if str(c[0]) in selected_choices] self.choices = choices return super(MultiSelectWidget, self).render_options([], selected_choices) class MyAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyAdminForm, self).__init__(*args, **kwargs) self.fields['m2m_field'].widget = MultiSelectWidget('m2m_field', is_stacked=False) class Meta: model = MyModel class MyAdmin(admin.ModelAdmin): form = MyAdminForm </code></pre> <p>which renders correctly.</p> <p>But I am not sure how to implement this <code>some_js_to_load_ajax_options.js</code> ajax part. Should I write my own jQuery snippet or modify <code>SelectFilter2</code> which comes with <code>admin/media/js</code>? Anybody been there before?</p> <p><strong>edit:</strong> Although not related to the core of the question, as I only want to override the field's widget, the shorter way is to use <code>formfield_overrides</code>:</p> <pre><code>class MultiSelectWidget(FilteredSelectMultiple): # as above class MyAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': MultiSelectWidget}, } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload