Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set width and input limit of NumberInput widget for IntegerField in a Django form

I'm looking for a way to change the width of the input box in a Django form.

The model code for a parameter looks like this:

my_integer = models.IntegerField('Window', default=50)

And, putting it into a form, the HTML code that is generated is this:

<input id="id_my_integer" name="my_integer" value="50" type="number">

And, the box is quite wide - maybe 20 characters.

If I add the code in the definition of the form class Meta:

widgets = {
  'my_integer': forms.TextInput(attrs={'size':'3', 'maxlength':'3'}),
}

I get a box that is 5-6 characters wide that lets me insert 3 characters and the HTML code changes the type to type='text' and the increment/decrement arrows disappear.

So, what I really want is a 3 character wide box, with a 3 character input limit, having the NumberInput widget's increment/decrement arrows. How do I do this?

like image 729
Photon Wrangler Avatar asked Oct 15 '25 18:10

Photon Wrangler


2 Answers

The arrow controls are a part of the NumberInput widget, so you'll have to use that. Unfortunately, in current HTML, there is no support for the size and maxlength attributes for the number input field <input type="number">.

The width of the field is easier to hack, you can simply override the CSS. You can use either px or ch as units, depending on what your requirement is. To have a 3 character wide input box, add 'style': 'width:3ch' to the attrs dictionary. I'm using 6ch in the example below because using exactly 3ch leaves no space for the increment-decrement buttons.

To limit the number of characters entered, a simple js script will work. Here's the entire solution.

The widget:

widgets = {
    'my_integer': forms.NumberInput(attrs={
        'id': 'number_field',    
        'style': 'width:6ch',
        'oninput': 'limit_input()'
    }),
}

Inside your template file displaying the form, add this small script:

<script type="text/javascript">
    function limit_input() {
        var field = document.getElementById("number_field");
        var max_length = 3;
        if (field.value.length > max_length) {
            field.value = field.value.slice(0, max_length); 
        }
    }
</script>
like image 79
Yash Tewari Avatar answered Oct 17 '25 06:10

Yash Tewari


Now in Django 2.1.7 you can use size in NumberInput attrs

widgets = {
    'bank_account_number': form.NumberInput(attrs={'size': '20'}),
}

and just simply replace the attrs with attrs={'style': 'width:6ch'} works very well too. thanks Yash Tewari!

like image 30
C.K. Avatar answered Oct 17 '25 07:10

C.K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!