How to make a form field numeric only in Django

When using forms from the Django model, I have an Integer field that is only numeric. But in the browser it looks like a text box into which I can enter β€œcharacters”. I want to make it only "numerical". How to do it? that is, users should be able to enter only numbers .

We can do this in one way by setting the field attribute.

1)

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

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

+6
source share
5 answers

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

In the shape of:

  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(); } } }); }); 
0
source

Django 1.6 has a NumberInput Widget, but 1.6 is currently unstable.

But you can 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: ... 
+10
source

Here is another solution:

  • Add validators to the model file
  • Add css class to fields in model form
  • Use jquery to change the type of the specified class to "number" on document / page load

IN MODEL:

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

IN MODEL FORM - add a jquery class

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

IN FILE / JS FILE

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

I know this is a bad old thread, add this for posterity

To work around this problem, save the following as 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 the template:

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

Of course you can extend the html5type function to other types

Caution: numeric fields must have the default value specified above to work

0
source

Instead of RegexValidator, give validation in form attributes only as ...

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

etc.

Otherwise, you have to handle the error in the views. It helped me try this simple method ... It will allow users to enter only the number only

0
source

Source: https://habr.com/ru/post/954658/


All Articles