#27993 closed Bug (fixed)
Impossible to clear an ArrayField with a forms.MultipleChoiceField
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 , 8 years ago
Triage Stage: | Unreviewed → Accepted |
---|
comment:2 by , 8 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
The fix is to add
SelectMultiple.value_omitted_from_data()
that always returnsFalse
, similar to 87c5e7efebd040aef0f0479ccf86877155bb5cea.