如何设置Django管理中TabularInline formset中的默认值(How to set

2019-08-17 13:03发布

如何设置Django管理的直列第一默认行/值?

    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]

但该行不工作

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

我如何使用Django管理员设置的默认值?

Answer 1:

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

从这里: 预填充的内联表单集?



Answer 2:

如果你需要的是定义为创建你可以重新定义的新形式的默认值empty_form一个财产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

现在,每次添加一个新的形式,它包含您使用它提供的初始数据。 我上的Django 1.5测试这一点。



文章来源: How to set default values in TabularInline formset in Django admin