hasattr(value, "contribute_to_class") returns KeyError: 'contribute_to_class' (Django 4.1)

594 Views Asked by At

A Django 1.1 / Python 2.7 project that I'm attempting to run on Python 3.10 / Django 4.1.

A Python related error (i.e. old import) or a django code error (i.e. missing field that's now mandatory) pops up, I fix it and rerun.

The current error, however, is coming from django/db/models/base.py, from this function -

def _has_contribute_to_class(value):
    # Only call contribute_to_class() if it's bound.
    return not inspect.isclass(value) and hasattr(value, "contribute_to_class")

I found this ticket - https://code.djangoproject.com/ticket/30309

that explains that hasattr is unreliable, but seems to be ignored.

Has anyone encountered this issue, and managed to find a solution other than staying on Django 1.1?

1

There are 1 best solutions below

0
On

hasattr Python2 vs hasattr Python3. They have different behavior

How works hasattr() in python 2:

try:
    getattr(foo, 'bar')
    return True
except:
    pass
return False #This is important part

How works hasattr() in python 3:

try:
    getattr(foo, 'bar')
    return True
except AttributeError as error:
    return False
raise AttributeError from error

It means - if you have any other problem in class - in python2 hasattr suppressed all. But Python3 give you an AttributeError Exception.

That's why i ask you to give us the code of class of your "value".

By the way: Django 4.1 call this method _has_contribute_to_class in ModelBase. Django 1.xx don't have this method and don't call it.