Django Admin ModelForm ManyToManyy add Button

Django Admin ManyToMany Add Button

In Django, Pythonby oesahLeave a Comment

Finally a working solution:

# forms.py


from django.contrib.admin.widgets import FilteredSelectMultiple, RelatedFieldWidgetWrapper

class MyForm(forms.ModelForm):
    m2m_field = forms.ModelMultipleChoiceField(queryset=None,label=('Select Entities'),)

    def __init__(self, *args, **kwargs):
        super(MyForm,self).__init__(*args, **kwargs)

        self.fields['m2m_field'].widget = RelatedFieldWidgetWrapper(
                                                FilteredSelectMultiple(('m2m_field'),False,),
                                                MyModel._meta.get_field('m2m_field').rel,
                                                self.admin_site)
        self.fields['m2m_field'].queryset = M2M_Model.objects.all()

    class Meta:
        model = MyModel
        fields = ['m2m_field',]
      
    class Media:
        ## media for the FilteredSelectMultiple widget
        css = {
            'all':('/static/admin/css/widgets.css',),
        }

    @property
    def media(self):
        extra = '.min'
        js = [
            'core.js',
            'vendor/jquery/jquery%s.js' % extra,
            'jquery.init.js',
            'admin/RelatedObjectLookups.js',
            'actions%s.js' % extra,
            'urlify.js',
            'prepopulate%s.js' % extra,
            'vendor/xregexp/xregexp.min.js',
        ]
        return forms.Media(js=['admin/js/%s' % url for url in js])

# some_template.html

{{ form.media }} {{ form.as_p }}

Leave a Comment