Duncan
Duncan

Reputation: 257

How to change NumberInput widget width in Django?

I'm trying to change the width of NumberInput and TextInput widgets:

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.FloatField: {'widget': NumberInput(attrs={'size':'10'})},
        models.CharField: {'widget': TextInput(attrs={'size':'10'})},
    }

It works good with TextInput widget but does not work with NumberInput widget.
How can I do it?

Upvotes: 3

Views: 1625

Answers (3)

Instead of size, you need to set style to change the width of NumberInput() as shown below:

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {                              # Instead of 'size'
        models.FloatField: {'widget': NumberInput(attrs={'style':'width:10ch'})},
        models.CharField: {'widget': TextInput(attrs={'size':'10'})},
    }

Upvotes: 0

PhönixGeist
PhönixGeist

Reputation: 319

You can change the width of your NumberInput at your form

class CreateBudgetItem(forms.ModelForm):

    class Meta:
        model = BudgetModelItems
        fields = ('budget_model',)
        widgets = {
            'budget_item_description': forms.Textarea(attrs={'rows': 2, 'cols': 50}),
            'budget_item_item': forms.NumberInput(attrs={'size': 6}),
            'budget_item_quantity': forms.NumberInput(attrs={'size': 6}),
        }

Upvotes: 1

Danilo Rodrigues
Danilo Rodrigues

Reputation: 413

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number

Elements of type "number" don't support form sizing attributes such as size. You'll have to resort to CSS to change the size of these controls.

Have you tried putting a class and create a css to fit the sizes?

It would look something like this:

models.FloatField: {'widget': NumberInput(attrs={'class':'form-number'})},

And in css you add this:

.form-number {
width: 10pt;
}

Upvotes: 2

Related Questions