Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Float Field input

Which is the best way to create a django form field that accepts floats and has the same functionality as a NumberInput? What I mean with same functionality is that django's NumberInput has arrows right next to the input that can increase or decrease the number and it also accepts min_value and max_value. If I use a TextInput widget I won't get this functionality. If I use NumberInput widget it wont work with floats:

homework = forms.FloatField(required=False, max_value=10, min_value=0, widget=NumberInput(attrs={'id': 'form_homework'}))

enter image description here

It doesn't include floats (i.e 5.5) when I click the + - buttons. Also, it doesn't show the float at all if I want to set the actual float (the homework's grade) as an initial value (using Jquery).

Any advice is welcome.

EDIT:

If I do:

class NumberInput(TextInput):
    input_type = 'number'

homework = forms.FloatField(required=False, max_value=10, min_value=0,
    widget=NumberInput(attrs={'id': 'form_homework', 'step': '0.1'}))

The 'step' attribute works but the max_value/min_value doesn't. If I do not define NumberInput that way and use the regular NumberInput, it doesn't work at all.

like image 512
Alejandro Veintimilla Avatar asked Jan 14 '15 18:01

Alejandro Veintimilla


Video Answer


2 Answers

You can do this by including NumberInput with your form widget and setting step attribute

homework = forms.FloatField(required=False, max_value=10, min_value=0, 
widget=forms.NumberInput(attrs={'id': 'form_homework', 'step': "0.01"})) 

Difference from above answer is missing forms reference with NumberInput of form

like image 153
Projesh Bhoumik Avatar answered Sep 30 '22 17:09

Projesh Bhoumik


Just specify "step" attribute as a widget attribute, this way:

homework = forms.FloatField(required=False, max_value=10, min_value=0, widget=NumberInput(attrs={'id': 'form_homework', 'step': "0.01"}))
like image 33
matagus Avatar answered Sep 30 '22 17:09

matagus