0

I have edited a bit of code from here 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']

Instead of running the code on the sku attribute of instance. I'd like to loop over multiple attributes

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]

which gives me the error in the title. How can I get the interpreter to interpret instance.name, instance.description and instance.deadline rather than instance.ro_field

Community
  • 1
  • 1
moadeep
  • 3,988
  • 10
  • 45
  • 72

1 Answers1

2

Change

return instance.ro_field

to

return getattr(instance, ro_field)

Documentation for getattr

jwodder
  • 54,758
  • 12
  • 108
  • 124