我最近问了this question,并按照最初所说的解决了我的问题。以下代码有效:
class FloatRangeField (FloatField):
"""A FloatField constrained to a given range."""
def __init__ (self, minimum, maximum, **kwargs):
minmax = [MinValueValidator (minimum), MaxValueValidator (maximum)]
self.minimum = minimum
self.maximum = maximum
kwargs ['validators'] = minmax
FloatField.__init__ (self, **kwargs)
def deconstruct (self):
name, path, args, kwargs = super () .deconstruct ()
kwargs ['minimum'] = self.minimum
kwargs ['maximum'] = self.maximum
del kwargs ['validators']
return name, path, args, kwargs
class AffinityField (FloatRangeField):
"""An affinity is a float from -1 (hate) to +1 (love)."""
def __init__ (self, **kwargs):
FloatRangeField.__init__ (self, -1.0, 1.0, **kwargs)
def deconstruct (self):
name, path, args, kwargs = super () .deconstruct ()
del kwargs ['minimum']
del kwargs ['maximum']
return name, path, args, kwargs
但是,我不认为这是完整的。我是Django的新手,但是我的理解是,添加验证器会约束模型愿意保存的数据,但与此分开的是,this answer indicates在表单级别进行了验证。
如果需要在表单级别上进行约束,则可以将min_value和max_value传递给表单字段:
myfloat = forms.FloatField(min_value=0.0, max_value=1.0)
我还没有任何可见的形式(只是开始学习!),所以我不知道是否有必要单独进行此操作,但是从 do 的听起来来看,我有传递min_value
和max_value
以及验证器对象。这是我的尝试:
class FloatRangeField (FloatField):
"""A FloatField constrained to a given range."""
def __init__ (self, minimum, maximum, **kwargs):
minmax = [MinValueValidator (minimum), MaxValueValidator (maximum)]
self.minimum = minimum
self.maximum = maximum
# Validators for the model
kwargs ['validators'] = minmax
# Arguments for the form validation
kwargs ['min_value'] = minimum
kwargs ['max_value'] = maximum
FloatField.__init__ (self, **kwargs)
def deconstruct (self):
name, path, args, kwargs = super () .deconstruct ()
kwargs ['minimum'] = self.minimum
kwargs ['maximum'] = self.maximum
del kwargs ['validators']
del kwargs ['min_value']
del kwargs ['max_value']
return name, path, args, kwargs
这引发异常:
FloatField.__init__ (self, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'min_value'
但是according to the documentation和min_value
参数 是预期的,所以我不知道此错误的真正含义。
我以为我了解字段解构函数的原理(从kwargs
删除那些在子类的__init__
中定义时不需要作为输入的东西),也许不是。
我如何使用min_value
和max_value
有什么问题?
答案 0 :(得分:0)
好像您混合了form fields和model fields。您在问题描述表单的FloatField
中提供的链接。
但是您要自定义的模型FloatField
默认没有min_value
和max_value
参数。