Last active
February 17, 2023 05:15
-
-
Save LowerDeez/e34ab2befaabe31882df67ce74315502 to your computer and use it in GitHub Desktop.
Django. Admin Tabular Inline initial data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ofinitial
data)