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

前端 未结 4 1304
灰色年华
灰色年华 2021-02-01 08:42

I have the following models:

class Message(models.Model):
    date = models.DateTimeField()
    user = models.ForeignKey(User)    
    thread = models.ForeignKey         


        
4条回答
  •  清酒与你
    2021-02-01 09:09

    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
    

提交回复
热议问题