Reputation: 8376
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
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 Element
s; I don't know if naming the field element_set
(or whatever the name of the reverse relation is) will be enough.
Upvotes: 3