0

let's say I've the following very simple models:

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)

I've been able to add an InLine to the Admin gui, but I'd like to use a SELECT component, so I can just select several Probes and assign them to the Customer. From this question:

one-to-many inline select with django admin

I know thanks to Luke's answer (last one) that I should create a custom Form and assign it to my ModelAdmin.form but I can not wonder how to tie it all together to make it work.

May anyone help?

Thanks a lot in advance.


OK, I came a step further, and now I've the field added to the Form, like this:

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)

but the initial values specified through "initial" are not being selected. What's wrong now? I assume that next will be to override the save() method to set the Probes on the Customer, am I right?

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 に答える