1

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?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Duncan
  • 191
  • 14

3 Answers3

2

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;
}
Danilo Rodrigues
  • 373
  • 3
  • 17
  • No I did not try it. I just think if it works with TextInput it should works with NumberInput as well... – Duncan Mar 25 '18 at 19:57
  • Apparently [it doesn't](https://stackoverflow.com/questions/12066436/styling-html5-input-type-number). – Paulo Almeida Mar 25 '18 at 20:03
  • I usually do not adjust appearances with widget. I just add class to fit everything into css later. I've never tested the size, so I can not tell you if it works with NumberInput. – Danilo Rodrigues Mar 25 '18 at 20:37
  • 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. – Danilo Rodrigues Mar 25 '18 at 21:14
0

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}),
        }
PhönixGeist
  • 309
  • 3
  • 16
0

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'})},
    }
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129