Opened 5 weeks ago

Closed 5 weeks ago

Last modified 5 weeks 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 (6)

comment:1 Changed 5 weeks ago by Tim Graham

Cc: Sergey Fedoseev added

comment:2 Changed 5 weeks ago by Matt Westcott

Has patch: set

comment:3 Changed 5 weeks ago by Simon Charette

Triage Stage: UnreviewedAccepted

comment:4 Changed 5 weeks ago by Tim Graham

Severity: NormalRelease blocker
Triage Stage: AcceptedReady for checkin

comment:5 Changed 5 weeks ago by Tim Graham <timograham@…>

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 Changed 5 weeks ago by Tim Graham <timograham@…>

In 58ad030d:

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

Regression in a68ea231012434b522ce45c513d84add516afa60.

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