[Fixed]-Django InlineModelAdmin – set inline field from request on save (set user field automatically) (save_formset vs save_model)

11👍

I have solved the first half of my question:

def save_formset(self, request, form, formset, change):
    if formset.model != InlineModel:
        return super(MainModelAdmin, self).save_formset(request, form, formset, change)
    instances = formset.save(commit=False)
    for instance in instances:
        if not instance.pk:
            instance.user = request.user
        instance.save()
    formset.save_m2m()

Now i’m interested in the bonus behavior:

  1. I’m required to select a user when adding a new inline due to validation rules. My best guess is to not include the ‘user’ field in my InlineModelInline.fields tuple, but then this won’t show the author for existing InlineModel instances. (Edit: adding ‘user’ to readonly_fields works here)

  2. (Edit) How can I make the existing inlines render ‘data’ as readonly, but still be able to edit it when adding a new inline?

👤EB.

1👍

It worked for me. This approach won’t allow me to delete Inline items.

def save_formset(self, request, form, formset, change):
    for form in formset.forms:
        form.instance.user = request.user
    formset.save()

0👍

To answer the Bonus Question: “How can I make the existing inlines render ‘data’ as readonly, but still be able to edit it when adding a new inline?”:

I use two inlines for the same model:

#admin.py
class InlineModelInline(admin.TabularInline):
    model = InlineModel
    extra = 1
    max_num = 1

#admin.py
class InlineModelExistingInline(admin.TabularInline):
    model = InlineModel
    readonly_fields = ('data', 'user') #All Fields here except pk
    can_delete = False
    extra = 0
    max_num = 0

class MainModelAdmin(admin.ModelAdmin):
    ...
    inlines = [InlineModelInline, InlineModelExistingInline]
    ...

Leave a comment