Django Admin - How to prefill add inline forms values sent through the querystring?

I am able to prefill a form using query-string parameters in Django Admin.

Let's say I have the following models:

class Book(models.Model):
    id = models.Autofield(primary_key=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    name = models.Charfield(max_length=200)

class Author(models.Model):
    id = models.Autofield(primary_key=True)
    name = models.Charfield(max_length=200)

If I go to /admin/library/author/add/?name=J.+K.+Rowling the author's name will be properly prefilled.

However if I add InlineForms like that:

class BookInline(StackedInline):
    model = Book
    extra = 0

class AuthorAdmin(ModelAdmin):
    inlines = [BookInline], AuthorAdmin)

I don't seem to be able to prefill books.

I tried: /admin/library/author/add/?name=J.+K.+Rowling&books-TOTAL_FORMS=1&books-0-name=Harry+Potter+and+the+Philosopher's+Stone

The author form is prefilled, but the first book form is not prefilled. Do you know how one manages that?

If you override get_formset_kwargs, you can prefill forms with some initial values:

class AuthorAdmin(ModelAdmin):
    inlines = [BookInline]

    def get_formset_kwargs(self, request, obj, inline, prefix):
        formset_params = super().get_formset_kwargs(request, obj, inline, prefix)
        if request.method == "GET":
            # Mind you, this will prefill all form of the formset with the same values.
            # But for our usecase it is sufficient.
            prefix_length = len(prefix) + 3
            initial_values = [{key[prefix_length:]: value for key, value in request.GET.items() if key.startswith(prefix)}]
        return formset_params

However, all extra form will contain the same values.

If you know how we can manage to use the index there, it would improve this answer.

Back to Top