Django Admin: Many-to-Many listbox doesn't show up with a through parameter

Neil picture Neil · May 18, 2010 · Viewed 10k times · Source

I have the following models:

class Message(models.Model):
    date = models.DateTimeField()
    user = models.ForeignKey(User)    
    thread = models.ForeignKey('self', blank=True, null=True)
    ...

class Forum(models.Model):
    name = models.CharField(max_length=24)
    messages = models.ManyToManyField(Message, through="Message_forum", blank=True, null=True)
    ...

class Message_forum(models.Model):
    message = models.ForeignKey(Message)
    forum = models.ForeignKey(Forum)
    status = models.IntegerField()
    position = models.IntegerField(blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True, null=True)

In the admin site, when I go to add/change a forum, I don't see the messages listbox as you'd expect. However, it shows up if I remove the 'through' parameter in the ManyToManyField declaration. What's up with that? I've registered all three models (plus Tag) to the admin site in admin.py.

TIA

Answer

Fedor picture Fedor · Jan 5, 2012

Documentation says:

When you specify an intermediary model using the through argument to a ManyToManyField, the admin will not display a widget by default.

But it's probably possible to display M2M fields in the admin change view even if the through attribute is defined.

class ForumAdminForm(forms.ModelForm):
    mm = forms.ModelMultipleChoiceField(
        queryset=models.Message.objects.all(),
        widget=FilteredSelectMultiple(_('ss'), False, attrs={'rows':'10'}))

    def __init__(self, *args, **kwargs):
        if 'instance' in kwargs:
            initial = kwargs.setdefault('initial', {})
            initial['mm'] = [t.service.pk for t in kwargs['instance'].message_forum_set.all()]

        forms.ModelForm.__init__(self, *args, **kwargs)

    def save(self, commit=True):
        instance = forms.ModelForm.save(self, commit)

        old_save_m2m = self.save_m2m
        def save_m2m():
            old_save_m2m()

            messages = [s for s in self.cleaned_data['ss']]
            for mf in instance.message_forum_set.all():
                if mf.service not in messages:
                    mf.delete()
                else:
                    messages.remove(mf.service)

            for message in messages:
                Message_forum.objects.create(message=message, forum=instance)

        self.save_m2m = save_m2m

        return instance

    class Meta:
        model = models.Forum

class ForumAdmin(admin.ModelAdmin):
    form = ForumAdminForm