Skip to content

Commit 0dc2e77

Browse files
neugedcodingjoe
authored andcommitted
Fix #128, add documentation on how to confifure select2 options
1 parent ebf5f76 commit 0dc2e77

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

docs/django_select2.rst

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,47 @@ plugin. It will handle both normal and heavy fields. Simply call
5555

5656
$('.django-select2').djangoSelect2();
5757

58+
Please replace all your ``.select2`` invocations with the here provided
59+
``.djangoSelect2``.
5860

59-
You can pass see `Select2 options <https://select2.github.io/options.html>`_ if needed::
6061

61-
$('.django-select2').djangoSelect2({placeholder: 'Select an option'});
62+
Configuring Select2
63+
-------------------
64+
65+
Select2 options can be configured either directly from Javascript or from within Django
66+
using widget attributes. `(List of options in the Select2 docs) <https://select2.org/configuration/options-api>`_.
67+
68+
To pass options in javascript
69+
70+
.. code-block:: javascript
71+
72+
$('.django-select2').djangoSelect2({
73+
minimumInputLength: 0,
74+
placeholder: 'Select an option',
75+
});
76+
77+
From Django, you can use ``data-`` attributes using the same names in camel-case and
78+
passing them to your widget. Select2 will then pick these up. For example when
79+
initialising a widget in a form, you could do:
80+
81+
.. code-block:: python
82+
83+
class MyForm(forms.Form):
84+
my_field = forms.ModelMultipleChoiceField(
85+
widget=ModelSelect2MultipleWidget(
86+
model=MyModel
87+
search_fields=['another_field']
88+
attrs={
89+
"data-minimum-input-length": 0,
90+
"data-placeholder": "Select an option",
91+
"data-close-on-select": "false",
92+
}
93+
)
94+
)
95+
96+
(If you do not want to initialize the widget, you could add the attributes by overriding
97+
a widget method and adding them in a super call, e.g. `get_context() <https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.get_context>`_)
6298

63-
Please replace all your ``.select2`` invocations with the here provided
64-
``.djangoSelect2``.
6599

66100
Security & Authentication
67101
-------------------------

0 commit comments

Comments
 (0)