Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#30254 closed Bug (fixed)

Custom model metaclasses cannot access the attribute dict in __init__

Reported by: Matt Westcott Owned by: nobody
Component: Database layer (models, ORM) Version: 2.2
Severity: Release blocker Keywords:
Cc: Sergey Fedoseev Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

In Django <=2.2, it is possible for models to define a custom metaclass (as a subclass of models.base.ModelBase) and access the attribute dict of the class being defined:

from django.db import models


class PageBase(models.base.ModelBase):
    def __init__(cls, name, bases, dct):
        super(PageBase, cls).__init__(name, bases, dct)
        if 'magic' in dct:
            print("enabling magic on %s" % (name))


class Page(models.Model, metaclass=PageBase):
    magic = True

    title = models.CharField(max_length=255)

As of commit a68ea231012434b522ce45c513d84add516afa60, this fails because all attributes without a contribute_to_class method are popped from the dict in ModelBase.__new__ .

(This pattern is used by Wagtail's Page model https://github.com/wagtail/wagtail/blob/3e1e67021e0a20783ed59e17b43e3c481897fce3/wagtail/core/models.py#L190 , so this is causing various failures against django stable/2.2.x.)

Change History (7)

comment:1 by Tim Graham, 5 years ago

Cc: Sergey Fedoseev added

comment:3 by Simon Charette, 5 years ago

Triage Stage: UnreviewedAccepted

comment:4 by Tim Graham, 5 years ago

Severity: NormalRelease blocker
Triage Stage: AcceptedReady for checkin

comment:5 by Tim Graham <timograham@…>, 5 years ago

Resolution: fixed
Status: newclosed

In 985e6c22:

[2.2.x] Fixed #30254 -- Allowed model metaclasses to access the attribute dict in init().

Regression in a68ea231012434b522ce45c513d84add516afa60.

Backport of 58ad030d05fa50cfed327368ab61defca3303e02 from master.

comment:6 by Tim Graham <timograham@…>, 5 years ago

In 58ad030d:

Fixed #30254 -- Allowed model metaclasses to access the attribute dict in init().

Regression in a68ea231012434b522ce45c513d84add516afa60.

comment:7 by Carlton Gibson <carlton.gibson@…>, 5 years ago

In 607ff4e:

Refs #30254 -- Added tests for Model.hash() inheritance.

Note: See TracTickets for help on using tickets.
Back to Top