django-select2
offre un modo per rendere il ArrayField
utilizzando Select2. Nella loro documentazione, l'esempio è per ArrayField
:
http://django-select2.readthedocs.io/en/latest/django_select2.html#django_select2.forms.Select2TagWidget
per rendere i valori già selezionati:
class ArrayFieldWidget(Select2TagWidget):
def render_options(self, *args, **kwargs):
try:
selected_choices, = args
except ValueError: # Signature contained `choices` prior to Django 1.10
choices, selected_choices = args
output = ['<option></option>' if not self.is_required and not self.allow_multiple_selected else '']
selected_choices = {force_text(v) for v in selected_choices.split(',')}
choices = {(v, v) for v in selected_choices}
for option_value, option_label in choices:
output.append(self.render_option(selected_choices, option_value, option_label))
return '\n'.join(output)
def value_from_datadict(self, data, files, name):
values = super().value_from_datadict(data, files, name)
return ",".join(values)
Per aggiungere il widget al modulo:
class MyForm(ModelForm):
class Meta:
fields = ['my_array_field']
widgets = {
'my_array_field': ArrayFieldWidget
}
Mi sto perdendo qualcosa? Dove stai sovrascrivendo il widget di amministrazione predefinito? Il frammento citato dal weblog trasforma l'ArrayField piuttosto limitato in qualcosa di utile e funziona molto bene. Tuttavia, sarebbe stato bello vedere che widget di amministrazione hai trovato fa il miglior uso di questo. Potrei dare Select2 a go. – Marakai
Ho ampliato l'esempio per essere più completo. – ropable