pythondjangodjango-modelsdjango-admin

Resize fields in Django Admin


Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars.

How can I tell the admin how wide a textbox should be, or the height of a TextField edit box?


Solution

  • You should use ModelAdmin.formfield_overrides.

    It is quite easy - in admin.py, define:

    from django.forms import TextInput, Textarea
    from django.db import models
    
    class YourModelAdmin(admin.ModelAdmin):
        formfield_overrides = {
            models.CharField: {'widget': TextInput(attrs={'size':'20'})},
            models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':40})},
        }
    
    admin.site.register(YourModel, YourModelAdmin)