Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you make django decimal field widgets (numberinput) increment differently

I am allowing someone to set prices for his pizza toppings, and I have a simple form which is the default DecimalField widget

models.py:

class Topping(models.Model):
    title       = models.CharField(max_length=60)
    description = models.CharField(max_length=50, blank=True, null=True)
    price       = models.DecimalField(max_digits=4, decimal_places=2, default=0.00)

forms.py:

class ToppingForm(forms.ModelForm):
    class Meta:
        model = Topping
        fields = ('title', 'price')

As of now, the widget allows clicking up or down to increase the price, but it defaults to 0.01, or a penny. This is useless, and I want them to be able to jump by 25 cents at a time. I don't know if I'm reading the wrong github, but the source shows nothing of interest, like a keyword arg to set increments:

https://github.com/django/django/blob/master/django/forms/widgets.py

class TextInput(Input):
    input_type = 'text'

    def __init__(self, attrs=None):
        if attrs is not None:
            self.input_type = attrs.pop('type', self.input_type)
        super(TextInput, self).__init__(attrs)


class NumberInput(TextInput):
    input_type = 'number'

Thank you

enter image description here

like image 736
codyc4321 Avatar asked Jul 29 '15 04:07

codyc4321


People also ask

What is decimal place in Django?

DecimalField is a field which stores a fixed-precision decimal number, represented in Python by a Decimal instance.

How can we make field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.

What is widget in Django?

A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <!DOCTYPE html> .


1 Answers

I think you can do this by adding the step attribute to the NumberInput widget.

class ToppingForm(forms.ModelForm):
    class Meta:
        model = Topping
        fields = ('title', 'price')
        widgets = {
            'price': forms.NumberInput(attrs={'step': 0.25}),
        }
like image 177
Rod Xavier Avatar answered Oct 01 '22 03:10

Rod Xavier