1👍
✅
You can add a custom form
to the PersonAdmin
class and override the __init__()
method to dynamically add a ModelChoiceField
for selecting the new family of a person.
Try this:
from django import forms
from django.contrib import admin
from .models import Family, Person
class PersonForm(forms.ModelForm):
new_family = forms.ModelChoiceField(
queryset=Family.objects.all(),
required=True,
label="New Family",
)
class Meta:
model = Person
fields = ["name", "family", "new_family"]
class PersonAdmin(admin.StackedInline):
model = Person
list_display = ("name", "family")
extra = 0
form = PersonForm # Here we Added custom form
class FamilyAdmin(admin.ModelAdmin):
model = Family
list_display = ("name",)
inlines = [PersonAdmin]
extra = 0
admin.site.register(Family, FamilyAdmin)
Source:stackexchange.com