在Django管理中使用内联模型时如何保存更新程序和创建器

时间:2018-12-17 23:50:56

标签: django

我正在尝试使用save_formset()函数在Django admin中保存更新者和创建者。我实施save_formset()的方式无法正常工作。它只是不断更新updated_by。就像我在change中使用save_model()参数一样,我认为如果我在save_formset()中执行相同的操作,它将可以正常工作。我错过了什么吗?

class ImageInline(admin.TabularInline):
    model = Image
    extra = 0
    readonly_fields = ('updated_by', 'created_by', 'updated_at', 'created_at', )


@admin.register(Store)
class StoreAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    form = StoreForm

    inlines = [
        ImageInline,
    ]

    ... 

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

        # For deleting
        for obj in formset.deleted_objects:
            obj.delete()

        # For adding
        for f in formset.forms:
            obj = f.instance
            if obj.image or obj.url:
                if not change:
                    obj.created_by = request.user
                else:
                    obj.updated_by = request.user
                obj.save()

        formset.save()

    def save_model(self, request, obj, form, change):
        # adding the entry for the first time
        if not change:
            obj.created_by = request.user
        # updating already existing record
        else:
            obj.updated_by = request.user

        obj.save()

1 个答案:

答案 0 :(得分:1)

如果您的内联实例已更新,save_formset()将起作用。 formset.save(commit=False)将返回更新的实例。您可以尝试这样:

def save_formset(self, request, form, formset, change):
    instances = formset.save(commit=False)
    for obj in instances:
        if obj.id:
            obj.created_by = request.user
        else:
            obj.updated_by = request.user
    formset.save()