pythondjangodjango-admintextinputdjango-widget

How to change size of CharField


This code is changing sizes of all CharFields in class. How I can change size of one CharField?

formfield_overrides = {
    models.CharField: {'widget': TextInput(attrs={'size': '20'})},
}

Solution

  • Define a custom model form that overrides the widget for your field:

    from django import forms
    
    class MyForm(forms.ModelForm):
        class Meta:
            widgets = {
                'my_field': forms.TextInput(attrs={'size': '20'}),
            }
    

    Then use your form in your model admin:

    class MyModelAdmin(admin.ModelAdmin):
        form = MyForm
        ...
    

    Note that setting TextInput(attrs={'size': '20'}) will only affect the way that the form field is displayed in the model admin. If you want to change the length of the column in the database you should set max_length instead.

    class MyModel(models.Model):
        my_field = models.CharField(max_length=20)