在保存之前将数据添加到admin modelform内联对象

时间:2015-05-27 18:58:35

标签: python django django-admin

关于下面的问题,我将如何为django管理员执行此操作?

Add data to ModelForm object before saving

示例:

class FooInlineModel(models.Model):
    bar = models.CharField()
    secret = models.CharField()


class FooInlineForm(forms.ModelForm):
    class Meta:
        model = FooInlineModel
        exclude = ('secret',)        


class FooInline(admin.TabularInline):
    pass


class FooAdmin(admin.ModelAdmin):
    inlines = (FooInline,)

这在逻辑上触发了IntegrityError,因为秘密被提交为NULL,如何在其中一个管理方法中手动填充该字段? e.g。

class ???:
    def ???:
        obj = form.save(commit=False)
        obj.secret = 'stackoverflow'
        obj.save()

1 个答案:

答案 0 :(得分:2)

好吧,我找到了感兴趣的方法:

class FooAdmin(admin.ModelAdmin):
    inlines = (FooInline,)

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)

        for instance in instances:
            if isinstance(instance, FooInlineModel):
                instance.secret = 'stackoverflow'
                instance.save()