Saturday, May 28, 2011

Dynamic Initial Value for Django Admin Inline Form

I am impressed with Django Admin Inline Form. Even more impressed by the simplicity to set the initial value for it.

One can easily set the initial value for Django Admin Add Form, via url get parameter. For example: http://localhost:8080/admin/myapp/mytable/?myfield_id=1

This will not work if myfield is within the inline form, instead of regular form. To do that, override admin.TabularInline formfield_for_foreignkey method.

Here is an example:

class MyTabInline(admin.TabularInline):
    model = models.MyModel
    extra = 1

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if == 'myfield':
            kwargs['initial'] = request.GET.get('myfield_id', '')
        return super(MyTabInline, self). 
                formfield_for_foreignkey(db_field, request, **kwargs)
Pretty simple.


  1. Just searched something like that :)

    Thanks a lot!

  2. Have you also tried this on ModelForms that declare additional fields?>

  3. @solvik: You're welcome.
    @Izz ad-Din: No, I have not. I am curious what exactly do you want to achieve. Perhaps you could elaborate more.