Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Last active February 17, 2023 05:15
Show Gist options
  • Save LowerDeez/e34ab2befaabe31882df67ce74315502 to your computer and use it in GitHub Desktop.
Save LowerDeez/e34ab2befaabe31882df67ce74315502 to your computer and use it in GitHub Desktop.
Django. Admin Tabular Inline initial data
from django.utils.functional import curry
class DetailsInline(admin.TabularInline):
model = Details
# formset = DetailsFormset
extra = 3
def get_formset(self, request, obj=None, **kwargs):
initial = []
if request.method == "GET":
initial.append({
'label': 'first name',
})
formset = super(DetailsInline, self).get_formset(request, obj, **kwargs)
formset.__init__ = curry(formset.__init__, initial=initial)
return formset
class Employee(models.Model):
username = models.CharField(_('Username'), max_length=150, null=False, blank=False)
email = models.CharField(_('Email'), max_length=150, null=False, blank=False)
class Details(models.Model):
employee = models.ForeignKey(Employee, verbose_name=_('Employee'), blank=False, null=False)
label = models.CharField(_('Label'), max_length=150, null=False, blank=False)
value = models.CharField(_('Value'), max_length=150, null=False, blank=False)
@serguitus
Copy link

Thanks for posting this. It was really helpful. Just a note: I see a little issue here: (maybe it is intentional. you can clarify)
In my case initials should be shown only when there are no Details Obj linked. Once you save your linked Details. If you reopen the changeForm, you will have duplicated Details (the ones already saved and the new initials) I added an extra check to put before line 11 of your script

if obj:
    saved = Details.objects.filter(employee=obj.id)
    if not saved:

this avoids suggesting related objects when already exist some.
Hope this helps someone :)

@ashishnitinpatil
Copy link

ashishnitinpatil commented Jun 8, 2019

Thank you @LowerDeez & @serguitus, I ended up with replacing line 10 with if request.method == "GET" and (not obj or not obj.id): and it worked like a charm :)

PS - Also, didn't require to mention formset (line 5) explicitly in my case (since all custom changes needed were just the addition of initial data)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment