[Django]-How to set initial data for Django admin model add instance form?

31👍

You need to include self as the first argument in your __init__ method definition, but should not include it when you call the superclass’ method.

def __init__(self, *args, **kwargs):
    # We can't assume that kwargs['initial'] exists! 
    if 'initial' not in kwargs:
        kwargs['initial'] = {}
    kwargs['initial'].update({'description': get_default_content()})
    super(FooAdminForm, self).__init__(*args, **kwargs)

Having said that, a model field can take a callable for its default, so you may not have to define a custom admin form at all.

class Foo(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(default=get_default_content)

43👍

Alasdair’s approach is nice but outdated. Radev’s approach looks quite nice and as mentioned in the comment, it strikes me that there is nothing about this in the documentation.

Apart from those, since Django 1.7 there is a function get_changeform_initial_data in ModelAdmin that sets initial form values:

def get_changeform_initial_data(self, request):
    return {'name': 'custom_initial_value'}
👤Wtower

15👍

More then 3 years later,
But actually what you should do is override admin.ModelAdmin formfield_for_dbfield .. like this:

class FooAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        field =  super(FooAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'description':
            field.initial = 'My initial description'
        elif db_field.name == 'counter':
            field.initial = get_counter() + 1
        return field

Cheers;

4👍

When adding new objects, it is convenient to use get_changeform_initial_data() as suggested by Wtower.

However, when changing existing objects, that does not work (see source).

In that case, you could extend ModelAdmin.get_form() as follows (using the OP’s example):

def get_form(self, request, obj=None, change=False, **kwargs):
    if obj and not obj.description:
        obj.description = get_default_content()
    return super().get_form(request, obj, change, **kwargs)
👤djvg

Leave a comment