DjangoAdmin MultipleSelect小部件不显示已选择的项目

时间:2018-07-16 09:41:20

标签: python django django-admin django-admin-filters

我有两个模型,LocationMachine

class Machine(models.Model):
    name = models.CharField(max_length=30, help_text='Name of machine')
    location = models.ForeignKey(Location, null=True, blank=True, on_delete=models.SET_NULL, help_text='ID of machine location')

    def __str__(self):
        return self.name

class Location(models.Model):
    name = models.CharField(max_length=30, help_text='Name of Location')

    def __str__(self):
        return self.name

Location中打开Django-Admin时,我不仅要选择1-N可用的计算机(正在运行),而且还希望看到已经选择的计算机(无法运行)

这是我给管理员的LocationForm

class LocationForm(forms.ModelForm):
    class Meta:
        model = Location # Parent Class
        fields = '__all__'

    #Select Only Machines without assigned location
    machines = forms.ModelMultipleChoiceField(queryset=Machine.objects.filter(location__isnull=True), required=False, widget=FilteredSelectMultiple(verbose_name=('Machines'), is_stacked=False))

    def __init__(self, *args, **kwargs):
        super(LocationForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['machines'].initial = self.instance.machine_set.all()

    def save(self, *args, **kwargs):
        instance = super(LocationForm, self).save(commit=False)
        self.fields['machines'].initial.update(location=None)
        instance.save()
        self.cleaned_data['machines'].update(location=instance)
        return instance

“所选机器”框始终为空,如何启用显示所选项目?我知道查询,但我不知道该把它放在哪里。

0 个答案:

没有答案