4👍
For anyone coming here looking for ways to hook into Django’s M2M inline form changes (like I was) here’s what I found simple and worked:
class HostelAdmin(admin.ModelAdmin):
inlines = [HostelGuestInline, HostelEntryPointInline]
def save_related(self, request, form, formsets, change):
for formset in formsets:
# Found this simple way to check dynamic class instance.
if formset.model == HostelGuest:
instances = formset.save(commit=False)
hostel = form.instance
for added_hostel_guest in formset.new_objects:
# Do something with new objects added (not tested this, though)
for deleted_hostel_guest in formset.deleted_objects:
do_something_with_deleted_guest_and_parent_instance(
deleted_hostel_guest.pk,
hostel.pk
)
super(HostelAdmin, self).save_related(request, form, formsets, change)
2👍
you can use Form
in your admin.TabularInline
.
this is example.
class HostelGuestForm(forms.ModelForm):
# set your code.
class HostelGuestInline(admin.TabularInline):
model=HostelGuest
form = HostelGuestForm
extra=4
if you want call external API, this is one of solutions.
you should type on your class HostelAdmin
def save_formset(self, request, form, formset, change):
if formset == formset_factory(HostelGuestForm):
# this `if` is check for formset is for HostelGuest
instances = formset.save(commit=False)
# it returns your added, changed, deleted instance
# if you don't have to check that instance is added or changed or deleted, below code is not required.
for instance in instances:
if instance.pk == None:
# this is added
elif:
# check `change` for is changed or deleted
formset.save_m2m()
else:
pass
the def save_formset()
is called by save_related()
, and the reason about not change save_related, change save_formset is for other inline form
. because inline formset can possible for be added not only HostelGuest
.
Source:stackexchange.com