Search code examples
pythonhtmldjangodjango-formsdjango-widget

Cannot overwrite step attribute of NumberInput field in django


I'm trying to make a NumberInput widget that has steps of 0.5, which is defined in the form as the following:

widgets = {
    "hours_per_day": widgets.NumberInput(attrs={'step': '0.5'})
}

However, the template is always rendered with the attribute step being 0.1. This widget is for a ModelForm's DecimalField. Why is the step attribute not changing?

Here's the (useful) code from the form:

class Registration_form(ModelForm):
    class Meta:
        model = Registration

        fields = [
            "hours_per_day",
        ]

        widgets = {
            "hours_per_day": widgets.NumberInput(attrs={'step': '1'})
        }

Solution

  • Try defining the NumberInput as a TextInput like so, and then step by 0.5:

    from django.forms.widgets import TextInput
    
    class NumberInput(TextInput):
        input_type = 'number'
    
    
    #Usage
    widgets = (
        'number_field': NumberInput(attrs={'min': '0', 'max': '10', 'step': '0.5'}),
    
    )