Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#27993 closed Bug (fixed)

Impossible to clear an ArrayField with a forms.MultipleChoiceField

Reported by: Olivier Dormond Owned by: heathervm
Component: Forms Version: 1.10
Severity: Normal Keywords: ArrayField postgresql MultipleChoiceField
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

While using a forms.MultipleChoiceField to represent an ArrayField, there is no way to clear the ArrayField. Unselecting all items from the rendred <select mutiple="multiple"> correctly leads to an empty list showing up in the form's cleaned_data but the value is ignored. The problem is that django.forms.models.construct_instance ignores the value due to django.forms.widgets.SelectMultiple (correctly) returning True from value_omitted_from_data(...).

The following small code example will demonstrate the issue by failing on the last assert.

from django.db import models
from django import forms
from django.contrib.postgres.fields import ArrayField

class TestModel(models.Model):
    array = ArrayField(models.CharField(max_length=10), default=list, blank=True)
    class Meta:
        app_label = 'test'

class TestForm(forms.ModelForm):
    array = forms.MultipleChoiceField(choices=(('one', 'One'), ('two', 'Two')), required=False)
    class Meta:
        model = TestModel
        fields = '__all__'

test_instance = TestModel(array=['one'])
assert test_instance.array == ['one']
test_form = TestForm(instance=test_instance)
test_form = TestForm(data=[], instance=test_instance)
assert test_form.is_valid()
assert test_form.cleaned_data == {'array': []}
updated_instance = test_form.save(commit=False)
assert updated_instance.array == []

Change History (6)

comment:1 by Tim Graham, 7 years ago

Triage Stage: UnreviewedAccepted

The fix is to add SelectMultiple.value_omitted_from_data() that always returns False, similar to 87c5e7efebd040aef0f0479ccf86877155bb5cea.

comment:2 by heathervm, 7 years ago

Owner: changed from nobody to heathervm
Status: newassigned

comment:3 by Tim Graham, 7 years ago

Has patch: set

comment:4 by Tim Graham <timograham@…>, 7 years ago

Resolution: fixed
Status: assignedclosed

In 7d1e237:

Fixed #27993 -- Fixed model form default fallback for SelectMultiple.

comment:5 by Tim Graham <timograham@…>, 7 years ago

In ff0c6b83:

[1.11.x] Fixed #27993 -- Fixed model form default fallback for SelectMultiple.

Backport of 7d1e23775344cc3dead03bd4af45f4fdf134b819 from master

comment:6 by Tim Graham <timograham@…>, 7 years ago

In 83331d1:

[1.10.x] Fixed #27993 -- Fixed model form default fallback for SelectMultiple.

Backport of 7d1e23775344cc3dead03bd4af45f4fdf134b819 from master

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