codyc4321
codyc4321

Reputation: 9682

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

Upvotes: 8

Views: 13880

Answers (2)

Tommy L
Tommy L

Reputation: 138

@codyc4321 Two Decimal places, define it in models.py:

YOUR_VAR = models.DecimalField(decimal_places=2, max_digits=4, blank=True, null=True)

Upvotes: -1

Rod Xavier
Rod Xavier

Reputation: 4043

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

Upvotes: 24

Related Questions