简体   繁体   中英

Getting model default value from modelForm in django

I have something like this in models.py

class A(models.Model):
    filed1 = CharField('label',max_length=3,default="default_1")

and 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

def setAttrs(object):
    for field_key,field_value in object.fields.items():

With last for loop i can access form fields and it works. But my question is can i get related field from model and than get its default value?

NEW UPDATE

Related to this question. I have same classes but field is custom (CustomCharField). In that custom field I have attribute readOnly="True". Can i somehow access to this attribute from last for loop?

In your for loop, you can access the default value using initial attribute of field_value .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM