Django管理员 - 如何保存内联?

时间:2011-08-08 21:31:21

标签: django django-admin inlines

我需要在admin中覆盖内联的save方法。保存照片时,我需要将用户ID添加到DB列。我不能在模型中制作,因为那里没有请求数据。我怎么能在管理员中,以某种方式获得nad设置用户ID?

2 个答案:

答案 0 :(得分:13)

我相信ModelAdmin上的save_formset方法是你应该使用的:

class ArticleAdmin(admin.ModelAdmin):
    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            instance.user = request.user
            instance.save()
        formset.save_m2m()

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset

答案 1 :(得分:0)

我对django(1.8)相对较新,并使用上述覆盖:

    def save_formset(self, request, form, formset, change):
    instances = formset.save(commit=False) # gets instance from memory and add to it before saving it
    for obj in formset.deleted_objects:
        obj.delete()
    for instance in instances:
        for form in formset: # cleaned_data is only available on the form, so you have to iterate over formset
            instance.modified_by = request.user
            instance.created_by = request.user
            instance.lowercase_enum_value_en = form.cleaned_data['enum_value_en'].lower()
            instance.save()
    formset.save_m2m()

即。在保存实例和表单之前添加它,但是当用户输入2行时,它总是保存最后的cleaning_data [' enum_value_en']。