How do you make django decimal field (numberinput) widgets differently

I am allowing someone to set prices for their pizza toppings and I have a simple form that 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')

      

At the moment, the widget allows you to click up or down to increase the price, but by default it is 0.01 or a penny. It's useless and I wish they could jump 25 cents at a time. I don't know if I am reading the wrong github, but the source is of no interest like the arg keyword to set the 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

enter image description here

+3


source to share


1 answer


I think you can do this by adding an attribute step

to the widget NumberInput

.



class ToppingForm(forms.ModelForm):
    class Meta:
        model = Topping
        fields = ('title', 'price')
        widgets = {
            'price': forms.NumberInput(attrs={'step': 0.25}),
        }

      

+5


source







All Articles