In Django admin, in a many-to-one relationship, show a selection list to select EXISTING "Many" from "One",

Imagine we have a model like this:

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

Container is One; Element is many.

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

 class Inline(admin.StackedInline): model = Element class ContainerAdmin(admin.ModelAdmin): inlines = (Inline,) admin.site.register(Container, ContainerAdmin) 

As a result, I get a set of forms that allows you to enter a new Element object in the Add Container form.
Instead, I would like to get the selected widget to select existing Element objects.

Is this possible without the introduction of an additional model?

+5
source share
1 answer

I think you can 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 something similar in my project, but I will let you know if I can find anything. You can also override the save() method on the form to actually save the selected Element s; I do not know if a name will be assigned in the element_set field (or whatever the name of the inverse relation).

+3
source

All Articles