Django admin - how to save inlines?
Asked Answered
V

2

5

I need to override save method of inlines in admin. While saving photos, I need to add user id to DB column. I cant make it in model because there is no request data there. How can I do it in admin, to somehow get nad set user id?

Virgel answered 8/8, 2011 at 21:31 Comment(0)
M
18

I believe the save_formset method on ModelAdmin is what you should use:

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

Misusage answered 8/8, 2011 at 22:27 Comment(0)
E
1

I'm relatively new to django (1.8) and using the above override:

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()

i.e. adding to it before saving the instance and form, however when the user enters 2 lines it always saves the last cleaned_data['enum_value_en'].

Exalted answered 3/8, 2016 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.