Code

Opened 9 months ago

Closed 9 months ago

#20813 closed Bug (worksforme)

max_length incorrectly passed to MultiValueField-derived class

Reported by: george_edison 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'

Attachments (0)

Change History (1)

comment:1 Changed 9 months ago by claudep

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to worksforme
  • Status changed from new to closed

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.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.