How to set default values in TabularInline formset in Django admin

前端 未结 3 1977
礼貌的吻别
礼貌的吻别 2021-02-05 22:58

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

    class Employee(models.Model):
        username = models.CharField(_(\'Username\'), max_length         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 23:23

    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.

提交回复
热议问题