Identify which inline form data comes from and set field when saved

I have model “Job” and a model “Node”. “Node” has a field “type”. From JobAdmin I have StackedInline for filling out the data, one for source and one for destination. When i press save I want to fill the field “type” with ‘source’ if the data originates from the sourceInline and ‘destination’ if the data is from destinationInline. One idea I had was to override the save_formset method but I can’t find any way to identify if data comes from source or destination form. Does this make sense and anyone have an idea on how to achive this?

(I intentionally left out some models and modeladmin to make it cleaner)

class Node(models.Model):
    job = models.ForeignKey(Job, related_name='nodes', on_delete=models.CASCADE)
    type = models.CharField(max_length=255, blank=True)
    host = models.CharField(max_length=200)
    port = models.IntegerField(default=22)


class SourceInlineFormSet(BaseInlineFormSet):
    def get_queryset(self):
        qs = super(SourceInlineFormSet, self).get_queryset()
        return qs.filter(type='source')


class SourceInline(admin.StackedInline):
    model = Node
    formset = SourceInlineFormSet
    fields = [('host', 'port', 'protocol', 'credential'), 'dir', 'filename_regex', 'rename', 'delete']


class JobAdmin(admin.ModelAdmin):
    list_display = ['name']

    fieldsets = (
        ("GENERAL", {
           'fields': ('name', 'active', 'created_date', 'changed_date')
        }),
    )

    inlines = (SourceInline, DestinationInline)

I think you should use a custom formset’s prefix. In your case you will have to instantiate two Formset form your SourceInlineFormset and give them a differet preffix to each one.
As documentation says this is useful when you want to use more than one Formset in a view

1 Like