Opened 2 years ago

Closed 2 years ago

Last modified 2 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 Changed 2 years ago by Tim Graham

Triage Stage: UnreviewedAccepted

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

comment:2 Changed 2 years ago by heathervm

Owner: changed from nobody to heathervm
Status: newassigned

comment:3 Changed 2 years ago by Tim Graham

Has patch: set

comment:4 Changed 2 years ago by Tim Graham <timograham@…>

Resolution: fixed
Status: assignedclosed

In 7d1e237:

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

comment:5 Changed 2 years ago by Tim Graham <timograham@…>

In ff0c6b83:

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

Backport of 7d1e23775344cc3dead03bd4af45f4fdf134b819 from master

comment:6 Changed 2 years ago by Tim Graham <timograham@…>

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