How to change NumberInput widget width in Django?

时间:2018-03-25 19:19:50

标签: django

I try 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?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

您可以在表格上更改NumberInput的宽度

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}),
        }