Skip to content

Support grouped choices. #1533

Closed
Closed
@ameyc

Description

@ameyc

Update from @tomchristie

Closing off some related tickets and rolling them into this one...


One of our models has a Choicefield with following choices:

TYPE_CHOICES = (
        ('Default', (
            (1, 'Option 1'),
            (2, 'Option 2'),
            (3, 'Option 3'))),
        (4, 'Option 4'))

Now in the serializer if i have something self.field.from_native(3), we get a ValidationError. Upon inspection of the DRF code we found that logic for valid_value method in the Choicefield is incorrect if you have nested sets with integer keys.

def valid_value(self, value):
        """
        Check to see if the provided value is a valid choice.
        """
        for k, v in self.choices:
            if isinstance(v, (list, tuple)):
                # This is an optgroup, so look inside the group for options
                for k2, v2 in v:
                    if value == smart_text(k2):
                        return True
            else:
                if value == smart_text(k) or value == k:
                    return True
        return False

Line if value == smart_text(k2): should really be: if value == smart_text(k2) or value == k2:

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions