[英]Getting model default value from modelForm in django
I have something like this in models.py
我在models.py
有这样的东西
class A(models.Model):
filed1 = CharField('label',max_length=3,default="default_1")
and forms.py
: 和forms.py
:
class AForm(ModelForm):
class Meta:
model = A
def __init__(self,*args,**kwargs):
super(AForm,self).__init__(*args,**kwargs)
setAttrs(self)
and function setAttrs
和功能setAttrs
def setAttrs(object):
for field_key,field_value in object.fields.items():
With last for loop i can access form fields and it works. 使用last for循环,我可以访问表单字段,并且可以正常工作。 But my question is can i get related field from model and than get its default value? 但是我的问题是我可以从模型中获取相关字段,而不是获取其默认值吗?
Related to this question. 与这个问题有关。 I have same classes but field is custom (CustomCharField). 我有相同的类,但字段是自定义(CustomCharField)。 In that custom field I have attribute readOnly="True". 在该自定义字段中,我具有属性readOnly =“ True”。 Can i somehow access to this attribute from last for loop? 我可以以某种方式从last for循环访问此属性吗?
In your for loop, you can access the default value using initial
attribute of field_value
. 在for循环中,您可以使用field_value
initial
属性访问默认值。
def setAttrs(object):
for field_key,field_value in object.fields.items():
print field_value.initial
Above will print initial/default value of each field. 上面将打印每个字段的初始值/默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.