我在Django模型和形式中有一个DecimalField,同样我有一个html格式的输入,逗号作为thounsand separator和小数点分隔符(123,456.78),用jquery插件Cleave.js格式化,但是当我试着保存我的表格,这个节目显示一条消息:输入一个数字。
我'想要保存表单中的数据,使用十进制值而不会丢失html中的格式。
对不起!我的英语太差了。
这是我的代码:
class Product(models.Model):
Price = models.DecimalField(
max_digits=17,
decimal_places=2,
default=0.00,
validators=[
MinValueValidator(
100.00,
message='>=100')])
class ProductForm(forms.ModelForm):
price = forms.DecimalField(
label='Price',
label_suffix=False,
max_digits=17,
decimal_places=2,
widget=forms.TextInput(
attrs={'placeholder': '123,456.78'})
)
class Meta:
model = Product
fields = [
'price'
]
class NewProduct(CreateView):
model = Product
form_class = ProductForm
template_name = 'new_product.html'
def get_success_url(self):
return reverse('products:new')
def get_queryset(self):
products = Product.objects.all()
return products
def get_context_data(self, **kwargs):
context = super(NewProduct, self).get_context_data(**kwargs)
context['products'] = self.get_queryset()
return context
<html lang="es">
<head>
<script src="{% static 'js/cleave.js' %}" type="text/javascript"></script>
</head>
<body>
<input type="text" id="price" class="price">
<script>
new Cleave('.price', {
numeral: true,
numeralDecimalMark: '.',
delimiter: ','
});
</script>
</body>
</html>
答案 0 :(得分:0)
好吧,我解决了这个问题,继承了DecimalField类,没有松散的原始行为,并创建了一个名为Thousands的新类(基于DecimalField类),用于覆盖to_python函数并用空字符串替换逗号&#39; &#39;
这是我的代码。
这对我有用,如果有人能写出更好的方法并在这里发表,那么我将非常感激。
同样,我的英语太糟糕了,抱歉!。
class Product(models.Model):
Price = models.DecimalField(
max_digits=17,
decimal_places=2,
default=0.00,
validators=[
MinValueValidator(
100.00,
message='>=100')])
from decimal import Decimal, DecimalException
class Thousands(forms.DecimalField):
def to_python(self, value):
if value in self.empty_values:
return None
if self.localize:
value = formats.sanitize_separators(value)
value = force_text(value).strip().replace(',', '')
try:
value = Decimal(value)
except DecimalException:
raise ValidationError(self.error_messages['invalid'], code='invalid')
return value
class ProductForm(forms.ModelForm):
price = Thousands(
label='Price',
label_suffix=False,
max_digits=17,
decimal_places=2,
widget=forms.TextInput(
attrs={'placeholder': '123,456.78'})
)
class Meta:
model = Product
fields = [
'price'
]
class NewProduct(CreateView):
model = Product
form_class = ProductForm
template_name = 'new_product.html'
def get_success_url(self):
return reverse('products:new')
def get_queryset(self):
products = Product.objects.all()
return products
def get_context_data(self, **kwargs):
context = super(NewProduct, self).get_context_data(**kwargs)
context['products'] = self.get_queryset()
return context
<html lang="es">
<head>
<script src="{% static 'js/cleave.js' %}" type="text/javascript"></script>
</head>
<body>
<form action="." method="post">
{% csrf_token %}
{{ form }}
</form>
<script>
new Cleave('.price', {
numeral: true,
numeralDecimalMark: '.',
delimiter: ','
});
</script>
</body>
</html>