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 chara
Here is a simple, yet flexible solution. Use a custom form to override some widgets.
# models.py
class Elephant(models.Model):
name = models.CharField(max_length=25)
age = models.IntegerField()
# forms.py
class ElephantForm(forms.ModelForm):
class Meta:
widgets = {
'age': forms.TextInput(attrs={'size': 3}),
}
# admin.py
@admin.register(Elephant)
class ElephantAdmin(admin.ModelAdmin):
form = ElephantForm
The widgets given in ElephantForm
will replace the default ones. The key is the string representation of the field. Fields not specified in the form will use the default widget.
Note that although age
is an IntegerField
we can use the TextInput
widget, because unlike the NumberInput
, TextInput
accepts the size
attribute.
This solution is described in this article.
It's well described in Django FAQ:
Q: How do I change the attributes for a widget on a field in my model?
A: Override the formfield_for_dbfield in the ModelAdmin/StackedInline/TabularInline class
class MyOtherModelInline(admin.StackedInline):
model = MyOtherModel
extra = 1
def formfield_for_dbfield(self, db_field, **kwargs):
# This method will turn all TextFields into giant TextFields
if isinstance(db_field, models.TextField):
return forms.CharField(widget=forms.Textarea(attrs={'cols': 130, 'rows':30, 'class': 'docx'}))
return super(MyOtherModelInline, self).formfield_for_dbfield(db_field, **kwargs)