About Dynamic Admin Inline Extras
Django inlines have a parameter extra which defines how many empty inline forms to show below the main form.
You can define the parameter dynamically using get_extra() method:
class AttachmentInline(admin.StackedInline):
model = Attachment
def get_extra(self, request, obj=None, **kwargs):
return 0 if obj and obj.attachment_set.exists() else 1
In our example, one empty inline Attachment form will be shown if no attachments exist yet.
Tips and Tricks Programming Django 5.2 Django 4.2 Django 3.2
Also by me
Django Messaging 🎅🏼
For Django-based social platforms.
Django Paddle Subscriptions 🎅🏼
For Django-based SaaS projects.
Django GDPR Cookie Consent 🎅🏼
For Django websites that use cookies.