Skip to content

Instantly share code, notes, and snippets.

@LowerDeez LowerDeez/admin.py
Created Oct 6, 2017

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

serguitus commented Oct 31, 2018

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

This comment has been minimized.

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
You can’t perform that action at this time.