Better ArrayField admin widget?

前端 未结 4 2056
抹茶落季
抹茶落季 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:50

    This is another version using the Django Admin M2M filter_horizontal widget, instead of the standard HTML select multiple.

    We use Django forms only in the Admin site, and this works for us, but the admin widget FilteredSelectMultiple probably will break if used outside the Admin. An alternative would be overriding the ModelAdmin.get_form to instantiate the proper form class and widget for the array field. The ModelAdmin.formfields_overrides is not enough because you need to instantiate the widget setting the positional arguments as shown in the code snippet.

    from django.contrib.admin.widgets import FilteredSelectMultiple
    from django.contrib.postgres.fields import ArrayField
    from django.forms import MultipleChoiceField
    
    
    class ChoiceArrayField(ArrayField):
        """
        A choices ArrayField that uses the `horizontal_filter` style of an M2M in the Admin
    
        Usage::
    
            class MyModel(models.Model):
                tags = ChoiceArrayField(
                    models.TextField(choices=TAG_CHOICES),
                    verbose_name="Tags",
                    help_text="Some tags help",
                    blank=True,
                    default=list,
                )
        """
    
        def formfield(self, **kwargs):
            widget = FilteredSelectMultiple(self.verbose_name, False)
            defaults = {
                "form_class": MultipleChoiceField,
                "widget": widget,
                "choices": self.base_field.choices,
            }
            defaults.update(kwargs)
            # Skip our parent's formfield implementation completely as we don't
            # care for it.
            return super(ArrayField, self).formfield(**defaults)
    

提交回复
热议问题