关于下面的问题,我将如何为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()
答案 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()