Opened 5 years ago

Closed 5 years ago

#30857 closed Bug (invalid)

When subclassing a model field, `max_length` cannot be passed as an argument to `self.__init__`.

Reported by: Robin (Robert) Thomas Owned by: nobody
Component: Documentation Version: 2.2
Severity: Normal Keywords: models fields
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Robin (Robert) Thomas)

class MyCustomField(models.CharField):
    def __init__(self, *args, **kwargs):
        super().__init__(max_length=60, *args, **kwargs)

class MyModel(models.Model)
    address_state = MyCustomField()

On attempting to migrate, I get:

super().__init__(max_length=60, *args, **kwargs)
TypeError: __init__() got multiple values for keyword argument 'max_length'

Using kwargs[max_length] works just fine. However, the documentation says that max_length should be able to be passed to super().__init__() as an argument:

https://docs.djangoproject.com/en/2.2/howto/custom-model-fields/#writing-a-field-subclass

Either the documentation is incorrect, or this is a bug.

Change History (2)

comment:1 by Robin (Robert) Thomas, 5 years ago

Description: modified (diff)

comment:2 by Mariusz Felisiak, 5 years ago

Component: UncategorizedDocumentation
Resolution: invalid
Status: newclosed
Summary: When subclassing a model field, `max_length` cannot be passed as an argument to `self.__init__`When subclassing a model field, `max_length` cannot be passed as an argument to `self.__init__`.
Type: UncategorizedBug

You can pass it directly but you have to add deconstruct() (see documentation):

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        del kwargs['max_length']
        return name, path, args, kwargs

Closing per TicketClosingReasons/UseSupportChannels.

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