0

假设我有以下非常简单的模型:

class Customer(models.Model):
        name = models.CharField(max_length=50)

class Probe(models.Model):
        OwnerInfo = models.CharField(max_length=50)
        comments = models.CharField(max_length=50)
        customer = models.ForeignKey(Customer, null=True, blank=True)

我已经能够将 InLine 添加到 Admin gui,但我想使用 SELECT 组件,所以我可以选择几个 Probes 并将它们分配给 Customer。从这个问题:

使用 django admin 进行一对多内联选择

多亏了卢克的回答(最后一个),我知道我应该创建一个自定义表单并将其分配给我的 ModelAdmin.form 但我不知道如何将它们结合在一起以使其工作。

有人可以帮忙吗?

提前非常感谢。


好的,我更进一步,现在我已将字段添加到表单中,如下所示:

from django.contrib import admin
from django import forms

from web_gui.models import Probe, Customer, Firmware

class CustomerForm(forms.ModelForm):

        probes = forms.ModelMultipleChoiceField(queryset=Probe.objects.all())

        def __init__(self, *args, **kwargs):
                super(CustomerForm, self).__init__(*args, **kwargs)
                self.fields['probes'].initial = [p.pk for p in Probe.objects.filter(customer_id=self.instance.pk)]

        class Meta:
                model = Customer


class CustomerAdmin(admin.ModelAdmin):
        form = CustomerForm

admin.site.register(Probe)
admin.site.register(Customer, CustomerAdmin)
admin.site.register(Firmware)

但是没有选择通过“initial”指定的初始值。现在怎么了?我假设接下来将覆盖 save() 方法以在客户上设置探测器,对吗?

4

1 回答 1

0

这是我想出的最好的解决方案。让我知道是否还有其他更好的方法可以实现这一目标:

from django.contrib import admin
from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple


from web_gui.models import Probe, Customer, Firmware

class CustomerForm(forms.ModelForm):

        probes = forms.ModelMultipleChoiceField(queryset = Probe.objects.all(), required=False)
        probes.widget = FilteredSelectMultiple("Probes",False,attrs={'rows':'10'})

        def __init__(self, *args, **kwargs):
                super(CustomerForm, self).__init__(*args, **kwargs)

                self.fields['probes'].initial = [p.pk for p in Probe.objects.filter(customer_id=self.instance.pk)]

        def save(self, force_insert=False, force_update=False, commit=True):
                c = super(CustomerForm, self).save(commit=False)
                c.probe_set = self.cleaned_data['probes']
                c.save()

                return c

        class Meta:
                model = Customer


class CustomerAdmin(admin.ModelAdmin):
        form = CustomerForm

admin.site.register(Probe)
admin.site.register(Customer, CustomerAdmin)
admin.site.register(Firmware)
于 2013-10-03T14:31:04.293 回答