gpt4 book ai didi

django - 扩展 django.forms.FloatField

转载 作者:行者123 更新时间:2023-12-02 07:09:44 26 4
gpt4 key购买 nike

我正在尝试创建一个自定义表单字段,其工作方式与浮点字段的所有意图和目的相同,但(默认情况下)输出不带尾随零的浮点值,例如33 而不是 33.0

我尝试像这样简单地扩展 django.forms.FloatField :

class CustomFloatField(django.forms.FloatField):

def to_python(self, value):
"""
Returns the value without trailing zeros.
"""
value = super(django.forms.FloatField, self).to_python(value)
# code to strip trailing zeros
return stripped_value

但这最终导致我收到验证错误。当我仔细观察 FloatField 类时,我注意到在它自己的 to_python() 方法中,它调用 super(IntegerField, self).to_python(value) 来检查以确保value 可以转换为 int,正是在这里我的代码似乎出错了。这让我彻底困惑了。如果 FloatField 必须尝试将其值转换为 int,那么 FloatField 到底如何工作? :)

很可能我在这里完全找错了方向,但如果有人能指出我正确的方向,我将不胜感激。

最佳答案

您的预感是正确的 - FloatField 并未真正调用 IntegerField 的 to_python 方法。为了说明到底发生了什么,

class A(object):
def __init__(self):
print "A initialized"

def to_python(self, value):
print "A: to_python"
return value

class B(A):
def __init__(self):
print "B initialized"

def to_python(self, value):
value = super(B, self).to_python(value)
print "B: value = "
print int(value)
return int(value)

class C(B):
def to_python(self, value):
value = super(B, self).to_python(value)
print "C: value = "
print float(value)
return float(value)

c = C()
c.to_python(5.5)

给出输出,

B initialized
A: to_python
C: value =
5.5

要将其放在上下文中,请使用 FloatField 的 to_python 中的行:

value = super(IntegerField, self).to_python(value)

实际上是调用Field的to_python,简单来说,

def to_python(self, value):
return value

在调用其余代码之前。这可能会进一步帮助您:Understanding Python super() with __init__() methods

关于django - 扩展 django.forms.FloatField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13014655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com