你如何使 django 十进制字段小部件(numberinput)以不同方式递增
how do you make django decimal field widgets (numberinput) increment differently
我允许某人为他的披萨配料定价,我有一个简单的表单,它是默认的 DecimalField 小部件
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')
截至目前,该小部件允许单击向上或向下以提高价格,但默认为 0.01,即一美分。这是没用的,我希望他们一次能跳 25 美分。我不知道我是否读错了 github,但源代码没有显示任何有趣的内容,例如设置增量的关键字 arg:
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'
谢谢
我认为您可以通过将 step
属性添加到 NumberInput
小部件来实现。
class ToppingForm(forms.ModelForm):
class Meta:
model = Topping
fields = ('title', 'price')
widgets = {
'price': forms.NumberInput(attrs={'step': 0.25}),
}
@codyc4321
两位小数,在models.py
中定义:
YOUR_VAR = models.DecimalField(decimal_places=2, max_digits=4, blank=True, null=True)
我允许某人为他的披萨配料定价,我有一个简单的表单,它是默认的 DecimalField 小部件
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')
截至目前,该小部件允许单击向上或向下以提高价格,但默认为 0.01,即一美分。这是没用的,我希望他们一次能跳 25 美分。我不知道我是否读错了 github,但源代码没有显示任何有趣的内容,例如设置增量的关键字 arg:
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'
谢谢
我认为您可以通过将 step
属性添加到 NumberInput
小部件来实现。
class ToppingForm(forms.ModelForm):
class Meta:
model = Topping
fields = ('title', 'price')
widgets = {
'price': forms.NumberInput(attrs={'step': 0.25}),
}
@codyc4321
两位小数,在models.py
中定义:
YOUR_VAR = models.DecimalField(decimal_places=2, max_digits=4, blank=True, null=True)