Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django中集中使用floatformat_Python_Django_Django Models_Django Templates - Fatal编程技术网

Python 如何在Django中集中使用floatformat

Python 如何在Django中集中使用floatformat,python,django,django-models,django-templates,Python,Django,Django Models,Django Templates,在我的项目中,我要求用户提供一些度量、价格和权重。我想将数据存储为两个十进制值。我想我应该使用DecimalField而不是FloatField,因为我不需要太多的精度 当我在模板中打印值时,我不希望打印零个非有效小数 示例: 10.00应该只显示10 10.05应显示为10.05 我不想在显示值的每个模板中使用floatformat过滤器,因为位置太多。因此,我想知道是否有某种方法可以影响以集中方式为所有应用程序呈现的值 谢谢你试用过django插件吗 你可能会在那里找到你想要的东西 编辑 你

在我的项目中,我要求用户提供一些度量、价格和权重。我想将数据存储为两个十进制值。我想我应该使用DecimalField而不是FloatField,因为我不需要太多的精度

当我在模板中打印值时,我不希望打印零个非有效小数

示例:

10.00应该只显示10

10.05应显示为10.05

我不想在显示值的每个模板中使用floatformat过滤器,因为位置太多。因此,我想知道是否有某种方法可以影响以集中方式为所有应用程序呈现的值


谢谢你试用过django插件吗

你可能会在那里找到你想要的东西

编辑

你是对的,人性化过滤器在这里不起作用。 在深入研究django内置的过滤器和标记之后,我找不到任何解决您问题的方法。因此,我认为您需要一个自定义过滤器。类似于

from django import template

register = template.Library()

def my_format(value):
    if value - int(value) != 0:
        return value
    return int(value)

register.filter('my_format',my_format)
my_format.is_safe = True
{% load my_filters %}
<html>
<body>
{{x|my_format}}
<br/>
{{y|my_format}}
</body>
</html>
在django模板中,您可以执行以下操作

from django import template

register = template.Library()

def my_format(value):
    if value - int(value) != 0:
        return value
    return int(value)

register.filter('my_format',my_format)
my_format.is_safe = True
{% load my_filters %}
<html>
<body>
{{x|my_format}}
<br/>
{{y|my_format}}
</body>
</html>

我希望这能有所帮助。

我终于找到了这个问题的答案,并将其发布在我的博客上:


我希望有人觉得它有用

那么模型中的属性如何:

_weight = models.DecimalField(...)
weight = property(get_weight)

def get_weight(self):
    if self._weight.is_integer():
        weight = int(self._weight)
    else:
        weight = self._weight
    return weight

我知道这个插件,但我看不出它对我有什么帮助。@maraujop你说得对。我想你需要一个定制的过滤器。请参阅答案新版。感谢msalvadores的努力,但我认为有一个名为floatformat的内置过滤器标签已经完成了这项工作。我的问题是,我不想编辑所有模板,每次渲染这些值时都要添加一个过滤器。这是300多倍。我可以做一个grep | sed,但我正在寻找一个集中的解决方案,这并不意味着改变模板、添加过滤器、标记或上下文处理器。在
10.00
中,您如何知道
.00
是否重要?“零非重要小数”假设有人声明了重要的内容。这将如何具体化?在数学上意义重大。小数点零不重要,这就是我对非有效小数的意思。我不希望在不改变任何东西的情况下显示零。@maraujop:“不改变任何东西”是一个人做出的判断。这是一个定义问题。2.0与2.0不同。数字可能很重要,因为工程师需要知道测量的准确性。不能随机删除尾随的零。你需要先定义有多少个零是有效的,然后你可以删除多余的不重要的零。我不是说Django应该随机删除零。我只是问是否有一种集中的方式让Django去做。因为这次我不关心尾随的零,我根本不需要它们。@maraujop:你为什么不使用整数?