Opened 11 years ago

Closed 11 years ago

#20813 closed Bug (worksforme)

max_length incorrectly passed to MultiValueField-derived class

Reported by: Nathan Osman Owned by: nobody
Component: Database layer (models, ORM) Version: 1.5
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have created a custom model field that looks something like this:

class TestModelField(models.CharField):
    __metaclass__ = models.SubfieldBase
    
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 10
        super(TestModelField, self).__init__(*args, **kwargs)

    # ... to_python and get_prep_value omitted ...
    
    def formfield(self, **kwargs):
        defaults = {'form_class': TestFormField,}
        defaults.update(kwargs)
        return super(TestModelField, self).formfield(**defaults)

The TestFormField class looks something like this:

class TestFormField(forms.MultiValueField):
    widget = TestWidget
    
    def __init__(self, *args, **kwargs):
        fields = (
            forms.IntegerField(min_value=0, max_value=15),
            forms.IntegerField(min_value=0, max_value=15),
        )
        super(TestFormField, self).__init__(fields, *args, **kwargs)
    
    # ... compress omitted ...

The problem lies in the fact that TestFormField.__init__ is receiving max_length in kwargs. Because this eventually gets passed along to Field.__init__ which doesn't have a max_length named parameter, an error is raised:

TypeError: __init__() got an unexpected keyword argument 'max_length'

Change History (1)

comment:1 by Claude Paroz, 11 years ago

Resolution: worksforme
Status: newclosed

You should either define your init method like this: def __init__(self, fields, max_length=None, *args, **kwargs) or pop the value in **kwargs (self.max_length = kwargs.pop('max_length', None)). See existing code in django/forms/fields.py.

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