Django — Admin Inline Styling / Widget Attrs / Overriding Widgets

Quickly style all of your inlines with formfield_for_dbfield

class PersonInline(admin.TabularInline):
	model = Person
	extra = 6
	def formfield_for_dbfield(self, db_field, **kwargs):
		attrs = { 'size': 15 }
		if db_field.attname == 'interest_level':
			attrs = { 'size': 2 }
		kwargs['widget'] = forms.TextInput(attrs=attrs)
		return super(PersonInline, self).formfield_for_dbfield(db_field,**kwargs)

I see this used for things like custom widgets, ReadOnlyWidget, ColoredWidget, etc, but I wanted a quick and dirty(?) way to fit more fields on my inlines, since the admin just overflows.

3 Comments

  1. Derek says:

    When I try this, I get an error on the :
    kwargs[‘widget’] = forms.TextInput(attrs=attrs)
    line, saying “forms is not defined”…

  2. Yuji says:

    That means you don’t have forms defined, just as if you started up python and wrote some variable that doesn’t exist.

    you need to import forms:
    from django import forms

  3. Isaac says:

    How would I modify this if I want some fields to be treated at TextInput, and some to be treated as Textarea?

Leave a reply to Derek Cancel reply