如何只在Django中创建一个表单字段数字

时间:2022-06-04 07:10:37

While using Django modelforms I have a Integer field which is numeric only. But in the browser it comes as a text field in which I can enter "characters". I want to make this only "numeric". How to do this ? i.e. users should be able to enter only numbers.

在使用Django模型时,我有一个只有数字的Integer字段。但是在浏览器中它是一个文本字段,我可以在其中输入“字符”。我想这只是“数字”。这个怎么做 ?即用户应该只能输入数字。

We can do it 1 way by setting the attribute of the field.

我们可以通过设置字段的属性来实现这一目的。

1)

1)

def __init__(self,*args,**kwargs):

        super(PropertyForm,self).__init__(*args, **kwargs)        
        self.fields['brokers_phone_number'].widget.attrs['type'] = "number"

This does not seem to work. I am using html 5 and the browser is Chrome. What am I doing wrong ? How can It be done better ?

这似乎不起作用。我使用的是html 5,浏览器是Chrome。我究竟做错了什么 ?怎么能做得更好?

5 个解决方案

#1


12  

Django 1.6 has a NumberInput Widget, but 1.6 is currently not stable.

Django 1.6有一个NumberInput Widget,但1.6目前还不稳定。

But you could try something like this:

但你可以尝试这样的事情:

from django.forms import ModelForm, CharField, TextInput

class PropertyForm(ModelForm):

    brokers_phone_number = CharField( widget=TextInput(attrs={'type':'number'}))

    class Meta:
     ...

#2


1  

Here is another solution:

这是另一个解决方案:

  • Add validators in the model file
  • 在模型文件中添加验证器
  • Add css class to fields in the model form
  • 将css类添加到模型表单中的字段
  • Use jquery to change type of the the above class to 'number' on document/page load
  • 使用jquery将上述类的类型更改为文档/页面加载上的“数字”

IN THE MODEL:

在模型中:

    exp_from = models.IntegerField(default=0,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(0)
        ])

    exp_to = models.IntegerField(default=1,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(1)
        ])

IN THE MODEL FORM - add a jquery class

在模型表单中 - 添加一个jquery类

self.fields['exp_from'].widget.attrs['class'] = "text_type_number"
self.fields['exp_to'].widget.attrs['class'] = "text_type_number"

IN THE HTML FILE/JS FILE

在HTML文件/ JS文件中

$(document).ready(function(){
   $('.text_type_number').attr('type', 'number');
});

#3


1  

In the end I ended up using a jQuery based solution. Question here. Instead of adding type I added a class "number" and added jquery number validation on it. But this is a hackish solution, especially when we have html 5 "number" in place. If anyone finds a way to do this please answer.

最后,我最终使用了基于jQuery的解决方案。问题在这里。而不是添加类型我添加了一个类“数字”,并在其上添加了jquery数字验证。但这是一个hackish解决方案,特别是当我们有html 5“数字”到位时。如果有人找到方法这样做,请回答。

In the form:

形式如下:

 def __init__(self,*args,**kwargs):
    super( PropertyFloorForm, self).__init__(*args, **kwargs)
    self.fields['number_of_units'].widget.attrs['class'] = "number"

In the template

在模板中

$(document).ready(function() {
    $(".number").keydown(function(event) {
        // Allow: backspace, delete, tab, escape, and enter
        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
            // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) ||
            // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        } else {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                event.preventDefault();
            }
        }
    });
});

#4


0  

I know this is a faily old thread, am adding this for posterity

我知道这是一个很老的话题,我为后代添加了这个

To get around this issue save the following as html5type.py

要解决此问题,请将以下内容另存为html5type.py

from django import template
register = template.Library()
def html5type(var):
    if isinstance(var, int):
        return 'number'
    else:
        return 'text'  

register.filter('html5type', html5type)

Then, in template:

{% load html5type %}
<input type={{ field.value | html5type }} ></input>

Of course you can extend the html5type function further for other types

当然,您可以进一步扩展html5type函数以用于其他类型

Caveat: Numeric fields need a default value for the above to work

警告:数字字段需要一个默认值才能使上述工作正常

#5


0  

Instead of RegexValidator, give validation in forms attributes only like...

而不是RegexValidator,只在表单属性中提供验证,如...

class StaffDetailsForm(forms.ModelForm):
    number = forms.CharField(required=True,widget=forms.TextInput(attrs={'class':'form-control' , 'autocomplete': 'off','pattern':'[0-9]+', 'title':'Enter numbers Only '}))

and so on...

等等...

Else you will have to handle the error in views. It worked for me try this simple method... This will allow users to enter only Number only

否则,您将不得不处理视图中的错误。它适用于我尝试这个简单的方法...这将允许用户只输入数字

#1


12  

Django 1.6 has a NumberInput Widget, but 1.6 is currently not stable.

Django 1.6有一个NumberInput Widget,但1.6目前还不稳定。

But you could try something like this:

但你可以尝试这样的事情:

from django.forms import ModelForm, CharField, TextInput

class PropertyForm(ModelForm):

    brokers_phone_number = CharField( widget=TextInput(attrs={'type':'number'}))

    class Meta:
     ...

#2


1  

Here is another solution:

这是另一个解决方案:

  • Add validators in the model file
  • 在模型文件中添加验证器
  • Add css class to fields in the model form
  • 将css类添加到模型表单中的字段
  • Use jquery to change type of the the above class to 'number' on document/page load
  • 使用jquery将上述类的类型更改为文档/页面加载上的“数字”

IN THE MODEL:

在模型中:

    exp_from = models.IntegerField(default=0,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(0)
        ])

    exp_to = models.IntegerField(default=1,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(1)
        ])

IN THE MODEL FORM - add a jquery class

在模型表单中 - 添加一个jquery类

self.fields['exp_from'].widget.attrs['class'] = "text_type_number"
self.fields['exp_to'].widget.attrs['class'] = "text_type_number"

IN THE HTML FILE/JS FILE

在HTML文件/ JS文件中

$(document).ready(function(){
   $('.text_type_number').attr('type', 'number');
});

#3


1  

In the end I ended up using a jQuery based solution. Question here. Instead of adding type I added a class "number" and added jquery number validation on it. But this is a hackish solution, especially when we have html 5 "number" in place. If anyone finds a way to do this please answer.

最后,我最终使用了基于jQuery的解决方案。问题在这里。而不是添加类型我添加了一个类“数字”,并在其上添加了jquery数字验证。但这是一个hackish解决方案,特别是当我们有html 5“数字”到位时。如果有人找到方法这样做,请回答。

In the form:

形式如下:

 def __init__(self,*args,**kwargs):
    super( PropertyFloorForm, self).__init__(*args, **kwargs)
    self.fields['number_of_units'].widget.attrs['class'] = "number"

In the template

在模板中

$(document).ready(function() {
    $(".number").keydown(function(event) {
        // Allow: backspace, delete, tab, escape, and enter
        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
            // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) ||
            // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        } else {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                event.preventDefault();
            }
        }
    });
});

#4


0  

I know this is a faily old thread, am adding this for posterity

我知道这是一个很老的话题,我为后代添加了这个

To get around this issue save the following as html5type.py

要解决此问题,请将以下内容另存为html5type.py

from django import template
register = template.Library()
def html5type(var):
    if isinstance(var, int):
        return 'number'
    else:
        return 'text'  

register.filter('html5type', html5type)

Then, in template:

{% load html5type %}
<input type={{ field.value | html5type }} ></input>

Of course you can extend the html5type function further for other types

当然,您可以进一步扩展html5type函数以用于其他类型

Caveat: Numeric fields need a default value for the above to work

警告:数字字段需要一个默认值才能使上述工作正常

#5


0  

Instead of RegexValidator, give validation in forms attributes only like...

而不是RegexValidator,只在表单属性中提供验证,如...

class StaffDetailsForm(forms.ModelForm):
    number = forms.CharField(required=True,widget=forms.TextInput(attrs={'class':'form-control' , 'autocomplete': 'off','pattern':'[0-9]+', 'title':'Enter numbers Only '}))

and so on...

等等...

Else you will have to handle the error in views. It worked for me try this simple method... This will allow users to enter only Number only

否则,您将不得不处理视图中的错误。它适用于我尝试这个简单的方法...这将允许用户只输入数字