[Django]-Django's Inline Admin: a 'pre-filled' field

3👍

There are a couple of ways to achieve this.

1: Set a default on the field in the model.

Django’s dynamic admin forms and inlines are smart enough to detect this and display it automatically as a default choice or entry.

class Book(models.Model):

    rating = models.IntegerField(default=0)

2: Use a custom form in your TabularInline class.

class BookInlineForm(models.ModelForm):

    class Meta:
        model = Book
        fields = ('rating', )

    def __init__(self, *args, **kwargs):
        initial = kwargs.pop('initial', {})
        # add a default rating if one hasn't been passed in
        initial['rating'] = initial.get('rating', 0)
        kwargs['initial'] = initial
        super(BookInlineForm, self).__init__(
            *args, **kwargs
        )


class BookTabularInline(admin.TabularInline):
    model = Book
    form = BookInlineForm


class ShelfAdmin(admin.ModelAdmin):
    inlines = (BookAdmin,)

Leave a comment