Better ArrayField admin widget?

前端 未结 4 1910
抹茶落季
抹茶落季 2020-12-30 22:42

Is there any way to make ArrayField\'s admin widget allow adding and deleting objects? It seems that by default, it is instead displayed just a text field, and uses comma se

4条回答
  •  有刺的猬
    2020-12-30 22:52

    django-select2 offers a way to render the ArrayField using Select2. In their documentation, the example is for ArrayField:

    http://django-select2.readthedocs.io/en/latest/django_select2.html#django_select2.forms.Select2TagWidget

    To render the already selected values:

    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 = ['' 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)
    

    To add the widget to your form:

    class MyForm(ModelForm):
    
        class Meta:
            fields = ['my_array_field']
            widgets = {
                'my_array_field': ArrayFieldWidget
            }
    

提交回复
热议问题