#35878: Allow to add M2M also in related-model form in admin site
-------------------------------+--------------------------------------
     Reporter:  David          |                    Owner:  (none)
         Type:  Uncategorized  |                   Status:  new
    Component:  contrib.admin  |                  Version:
     Severity:  Normal         |               Resolution:
     Keywords:                 |             Triage Stage:  Unreviewed
    Has patch:  0              |      Needs documentation:  0
  Needs tests:  0              |  Patch needs improvement:  0
Easy pickings:  0              |                    UI/UX:  0
-------------------------------+--------------------------------------
Comment (by David):

 To make it work my "workaround" is

 {{{#!python
 from django import forms
 from django.contrib import admin
 from django.contrib.admin import widgets
 from .models import ModelA, ModelB

 class ModelAForm(forms.ModelForm):
     others_set = forms.ModelMultipleChoiceField(
         queryset=ModelB.objects.all(),
         required=False,
         widget=widgets.FilteredSelectMultiple(verbose_name='ModelB',
 is_stacked=False)
     )
     def _save_m2m(self):
         super()._save_m2m()
         self.instance.others_set.set(self.cleaned_data['others_set'],
 clear=True)

 @admin.register(ModelA)
 class ModelAAdmin(admin.ModelAdmin):

     @property
     def form(self):
         class AdminM2MAdminForm(ModelAForm):
             """Helper to display the right widget in admin"""

         AdminM2MAdminForm.declared_fields['others_set'].widget =
 widgets.RelatedFieldWidgetWrapper(
             AdminM2MAdminForm.declared_fields['others_set'].widget,
             ModelB.others.through._meta.get_field('modelb').remote_field,
             self.admin_site,
         )
         return AdminM2MAdminForm
 }}}

 This way the admin displays the "+" button which points to ModelB form in
 ModelA admin. Not trivial and quite fragile (some APIs are not
 documented).
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35878#comment:1>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/django-updates/01070192de53d9d9-bf76b0d9-8a8c-4a11-8633-5e4e63f98e32-000000%40eu-central-1.amazonses.com.

Reply via email to