对象'项'没有属性'ro_field'

时间:2015-04-17 12:45:54

标签: python

我已经在这里编辑了一些代码In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

def clean_sku(self):
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            return instance.sku
        else:
            return self.cleaned_data['sku']

而不是在实例的sku属性上运行代码。我想循环遍历多个属性

readonly = ['name', 'description', 'deadline']

def clean(self):
        instance = getattr(self, 'instance', None)
        for ro_field in self.readonly:
            if instance and instance.pk:
                return instance.ro_field
            else:
                return self.cleaned_data[ro_field]

这给了我标题中的错误。如何让口译员解释instance.nameinstance.descriptioninstance.deadline而不是instance.ro_field

1 个答案:

答案 0 :(得分:2)

更改

return instance.ro_field

return getattr(instance, ro_field)

Documentation for getattr