0

If I accidentally typo the field name on a model, I want to raise an exception rather than silently failing:

obj = MyModel()
obj.fieldsdoesnotexist = 'test' # No exception is raised

How can I make Django raise exceptions when setting invalid fields?

Flash
  • 15,945
  • 13
  • 70
  • 98

1 Answers1

2

You can achieve this by creating Mixin that overrides setattr behavior like this:

class ValidateFieldNamesMixin:
    def __setattr__(self, name, value):
        if not hasattr(self, name):
            raise ValueError('Invalid field name!')
        return super().__setattr__(name, value)

And you must inherit this mixin in your MyModel class:

class MyModel(ValidateFieldNamesMixin, Model):
    # etc
Dima Kudosh
  • 7,126
  • 4
  • 36
  • 46
  • Thanks! Do you know why it allows me to set the invalid field in the first place? – Flash Mar 13 '17 at 09:25
  • It's normal python behavior that you can set new attribute/method to your class. So if you want to change it you must override setattr. – Dima Kudosh Mar 13 '17 at 09:34