Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default values in TabularInline formset in Django admin

How to set first default rows/values in django admin's inline?

    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)


    class DetailsFormset(forms.models.BaseInlineFormSet):
        def __init__(self, *args, **kwargs):
                self.initial = [
{ 'label': 'first name'},  
{'label': 'last name'}, 
{'label': 'job',}]
            super(DetailsFormset, self).__init__(*args, **kwargs)

    class DetailsInline(admin.TabularInline):
        model = Details
        formset = DetailsFormset
        fieldsets = [
                ['', {'fields': ['employee', 'label', 'value']}]
        ]

    class EmployeeAdmin(admin.ModelAdmin):
        inlines = [DetailsInline]

but this row doesn't work

    self.initial = [
{ 'label': 'first name'},  
{'label': 'last name'}, 
{'label': 'job',}]

How do I set default values using django admin?

like image 363
jargalan Avatar asked Mar 13 '13 04:03

jargalan


2 Answers

If what you need is to define default values for the new forms that are created you can redefine the empty_form property of a InlineFormSet:

class MyDefaultFormSet(django.forms.models.BaseInlineFormSet):
    @property
    def empty_form(self):
       form = super(MyDefaultFormSet, self).empty_form
       # you can access self.instance to get the model parent object
       form.fields['label'].initial = 'first name'
       # ...
       return form

 class DetailsInline(admin.TabularInline):
    formset = MyDefaultFormSet

Now, every time you add a new form it contains the initial data you provided it with. I've tested this on django 1.5.

like image 152
Rolando Urquiza Avatar answered Oct 15 '22 23:10

Rolando Urquiza


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

From here: Pre-populate an inline FormSet?

like image 44
catherine Avatar answered Oct 15 '22 21:10

catherine