Ad N
Ad N

Reputation: 8376

In Django admin, in a Many-to-One relationship, show a select list to pick EXISTING "Many" from the "One"

Imagine we have a model like that:

class Container(models.Model):
    name = models.CharField(max_length=60)

class Element(models.Model):
    container = models.ForeignKey(Container, blank=True, null=True)

Container is the One, Element is the many.

In Django admin, if I add a StackedInline with model=Element to the inlines of the Container model admin:

class Inline(admin.StackedInline):
    model = Element

class ContainerAdmin(admin.ModelAdmin):
    inlines = (Inline,)

admin.site.register(Container, ContainerAdmin)

I end up with a formset allowing me to enter new Element objects on the Add Container form.
Instead, I would like to be given a select widget, to pick existing Element objects.

Is that possible without introducing an extra model ?

Upvotes: 9

Views: 2386

Answers (1)

Alex Van Liew
Alex Van Liew

Reputation: 1369

I think you should be able to do it like this:

class ContainerAdminForm(forms.ModelForm):
    class Meta:
        model = Container
        fields = ('name',)
    element_set = forms.ModelMultipleChoiceField(queryset=Element.objects.all())

class ContainerAdmin(admin.ModelAdmin):
    form = ContainerAdminForm

# register and whatnot

I don't know that I have anything like this in my project, but I'll let you know if I find something. You may also have to override the save() method on the form in order to actually save the selected Elements; I don't know if naming the field element_set (or whatever the name of the reverse relation is) will be enough.

Upvotes: 3

Related Questions