Skip to content

Commit d11b994

Browse files
authored
docs: ArrayWidget choices (#1039)
1 parent d9fccc9 commit d11b994

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

docs/widgets/array.md

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: ArrayWidget
33
order: 1
4-
description: ArrayWidget for ArrayField
4+
description: Learn how to use Django Unfold's ArrayWidget to efficiently manage and display ArrayField data in your Django admin interface with support for both text inputs and dropdown lists.
55
---
66

77
# Unfold widget ArrayWidget
@@ -15,22 +15,38 @@ INSTALLED_APPS = [
1515
]
1616
```
1717

18-
Below you can see how to use ArrayWidget in your admin class. In this example all `ArrayField` fields will use `ArrayWidget` to render input field. In case `choices` are provided for the widget, dropdown list will be used instead of text input.
18+
Below you can see how to use ArrayWidget in your admin class. In this example, all `ArrayField` fields will use `ArrayWidget` to render input fields. If `choices` are provided for the widget, a dropdown list will be used instead of a text input.
19+
20+
When it comes to providing choices for the widget, by default the widget does not have any information about the field's choices, so it is mandatory to provide them manually. You can do this in the `get_form` method where the widget is initialized with the `choices` parameter.
1921

2022
```python
2123
# admin.py
2224

2325
from django.contrib import admin
2426
from django.contrib.postgres.fields import ArrayField
27+
from django.db.models import TextChoices
28+
from django.utils.translation import gettext_lazy as _
29+
2530
from unfold.admin import ModelAdmin
2631
from unfold.contrib.forms.widgets import ArrayWidget
2732

2833

34+
class SomeChoices(TextChoices):
35+
OPTION_1 = "OPTION_1", _("Option 1")
36+
OPTION_2 = "OPTION_2", _("Option 2")
37+
38+
2939
@admin.register(MyModel)
3040
class CustomAdminClass(ModelAdmin):
3141
formfield_overrides = {
3242
ArrayField: {
3343
"widget": ArrayWidget,
3444
}
3545
}
46+
47+
# If you need to provide choices for the widget, you can do it in the get_form method.
48+
def get_form(self, request, obj=None, change=False, **kwargs):
49+
form = super().get_form(request, obj, change, **kwargs)
50+
form.base_fields["array_field"].widget = ArrayWidget(choices=SomeChoices)
51+
return form
3652
```

0 commit comments

Comments
 (0)