如何以Django形式为IntegerField设置NumberInput小部件的宽度和输入限制 [英] How to set width and input limit of NumberInput widget for IntegerField in a Django form

查看:386
本文介绍了如何以Django形式为IntegerField设置NumberInput小部件的宽度和输入限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种以Django形式更改输入框宽度的方法.

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

参数的模型代码如下:

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

并将其放入表单中,生成的HTML代码是这样的:

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">

并且盒子很宽-可能是20个字符.

and the box is quite wide - maybe 20 characters.

如果我在表单类Meta的定义中添加代码:

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

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

我得到一个5到6个字符宽的框,允许我插入3个字符,HTML代码将类型更改为type ='text',并且递增/递减箭头消失.

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.

因此,我真正想要的是一个3个字符的宽框,输入限制为3个字符,具有NumberInput小部件的增/减箭头.我该怎么做?

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?

推荐答案

箭头控件是NumberInput小部件的一部分,因此您必须使用它.不幸的是,在当前的HTML中,数字输入字段<input type="number">不支持sizemaxlength属性.

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">.

该字段的宽度更容易破解,您可以简单地覆盖CSS.您可以根据需要使用pxch作为单位.要具有3个字符的输入框,请在attrs词典中添加'style': 'width:3ch'.我在下面的示例中使用6ch,因为恰好使用3ch不会为增减按钮留出空间.

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.

要限制输入的字符数,可以使用简单的js脚本.这是整个解决方案.

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

小部件:

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

在显示表单的template文件中,添加以下小脚本:

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>

这篇关于如何以Django形式为IntegerField设置NumberInput小部件的宽度和输入限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆