本文介绍了Django Admin:“多对多"列表框未显示通过参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

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)

在管理站点中,当我去添加/更改论坛时,没有看到您期望的消息列表框.但是,如果我在ManyToManyField声明中删除"through"参数,就会显示出来.那是怎么回事?我已经在admin.py中将所有三个模型(加标签)注册到管理站点.

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

推荐答案

文档说:

但是,即使定义了through属性,也有可能在管理更改视图中显示M2M字段.

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

这篇关于Django Admin:“多对多"列表框未显示通过参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:10