user2298943
user2298943

Reputation: 632

add data to admin modelform inline object before saving

In relation to the question below, how would I do this for the django admin?

Add data to ModelForm object before saving

Example:

class FooInlineModel(models.Model):
    bar = models.CharField()
    secret = models.CharField()


class FooInlineForm(forms.ModelForm):
    class Meta:
        model = FooInlineModel
        exclude = ('secret',)        


class FooInline(admin.TabularInline):
    pass


class FooAdmin(admin.ModelAdmin):
    inlines = (FooInline,)

This logically triggers an IntegrityError because secret is submitted NULL, how do I manually populate the field in one of the admin methods? e.g.

class ???:
    def ???:
        obj = form.save(commit=False)
        obj.secret = 'stackoverflow'
        obj.save()

Upvotes: 0

Views: 562

Answers (1)

user2298943
user2298943

Reputation: 632

Alright I found the method, for those interested:

class FooAdmin(admin.ModelAdmin):
    inlines = (FooInline,)

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

        for instance in instances:
            if isinstance(instance, FooInlineModel):
                instance.secret = 'stackoverflow'
                instance.save()

Upvotes: 4

Related Questions