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)
@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