Widgets

Class Diagram

Inheritance diagram of django_select2.widgets

Reference

Contains all the Django widgets for Select2.

class django_select2.widgets.Select2Mixin(**kwargs)[source]

Bases: object

The base mixin of all Select2 widgets.

This mixin is responsible for rendering the necessary Javascript and CSS codes which turns normal <select> markups into Select2 choice list.

The following Select2 otions are added by this mixin:-

  • minimumResultsForSearch: 6
  • placeholder: ''
  • allowClear: True
  • multiple: False
  • closeOnSelect: False

Note

Many of them would be removed by sub-classes depending on requirements.

__init__(**kwargs)[source]

Constructor of the class.

The following additional kwarg is allowed:-

Parameters:select2_options (dict or None) –

This is similar to standard Django way to pass extra attributes to widgets. This is meant to override values of existing options.

Example:

class MyForm(ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'name': Select2WidgetName(select2_options={
                'minimumResultsForSearch': 10,
                'closeOnSelect': True,
                })
        }

Tip

You cannot introduce new options using this. For that you should sub-class and overried init_options(). The reason for this is, few options are not compatible with each other or are not applicable in some scenarios. For example, when Select2 is attached to <select> tag, it can get if it is multiple or single valued from that tag itself. In this case if you specify multiple option then not only it is useless but an error in Select2 JS’ point of view.

There are other such intricacies, based on which some options are removed. By enforcing this restriction we make sure to not break the code by passing some wrong concotion of options.

options = {'minimumResultsForSearch': 6, 'allowClear': True, 'closeOnSelect': False, 'placeholder': '', 'multiple': False}

The options listed in this are rendered as JS map and passed to Select2 JS code. The complete description of theses options are available in Select2 JS’ site.

init_options()[source]

Sub-classes can use this to pass additional options to Select2 JS library.

Example:

def init_options(self):
    self.options['createSearchChoice'] = JSFunction('Your_js_function')

In the above example we are setting Your_js_function as Select2’s createSearchChoice function.

Tip

If you want to run Your_js_function in the context of the Select2 DOM element, i.e. this inside your JS function should point to the component instead of window, then use JSFunctionInContext instead of JSFunction.

set_placeholder(val)[source]

Placeholder is a value which Select2 JS library shows when nothing is selected. This should be string.

Returns:None
get_options()[source]
Returns:Dictionary of options to be passed to Select2 JS.
Return type:dict
render_select2_options_code(options, id_)[source]

Renders options for Select2 JS.

Returns:The rendered JS code.
Return type:unicode
render_js_code(id_, *args)[source]

Renders the <script> block which contains the JS code for this widget.

Returns:The rendered JS code enclosed inside <script> block.
Return type:unicode
render_inner_js_code(id_, *args)[source]

Renders all the JS code required for this widget.

Returns:The rendered JS code which will be later enclosed inside <script> block.
Return type:unicode
render(name, value, attrs=None, choices=())[source]

Renders this widget. Html and JS code blocks all are rendered by this.

Returns:The rendered markup.
Return type:unicode
class django_select2.widgets.Select2Widget(**kwargs)[source]

Bases: django_select2.widgets.Select2Mixin, django.forms.widgets.Select

Drop-in Select2 replacement for forms.Select.

Following Select2 option from Select2Mixin.options is removed:-

  • multiple
class django_select2.widgets.Select2MultipleWidget(**kwargs)[source]

Bases: django_select2.widgets.Select2Mixin, django.forms.widgets.SelectMultiple

Drop-in Select2 replacement for forms.SelectMultiple.

Following Select2 options from Select2Mixin.options are removed:-

  • multiple
  • allowClear
  • minimumResultsForSearch
class django_select2.widgets.MultipleSelect2HiddenInput(attrs=None)[source]

Bases: django.forms.widgets.TextInput

Multiple hidden input for Select2.

This is a specialized multiple Hidden Input widget. This includes a special JS component which renders multiple Hidden Input boxes as there are values. So, if user suppose chooses values 1, 4 and 9 then Select2 would would write them to the primary hidden input. The JS component of this widget will read that value and will render three more hidden input boxes each with values 1, 4 and 9 respectively. They will all share the name of this field, and the name of the primary source hidden input would be removed. This way, when submitted all the selected values would be available as list.

class django_select2.widgets.HeavySelect2Mixin(**kwargs)[source]

Bases: django_select2.widgets.Select2Mixin

The base mixin of all Heavy Select2 widgets. It sub-classes Select2Mixin.

This mixin adds more Select2 options to Select2Mixin.options. These are:-

  • minimumInputLength: 2

  • initSelection: JSFunction('django_select2.onInit')

  • ajax:
    • dataType: 'json'
    • quietMillis: 100
    • data: JSFunctionInContext('django_select2.get_url_params')
    • results: JSFunctionInContext('django_select2.process_results')

Tip

You can override these options by passing select2_options kwarg to __init__().

__init__(**kwargs)[source]

Constructor of the class.

The following kwargs are allowed:-

Parameters:

Tip

When data_view is provided then it is converted into Url using reverse().

Warning

Either of data_view or data_url must be specified, else ValueError would be raised.

Parameters:
  • choices (list or tuple) – The list of available choices. If not provided then empty list is used instead. It should be of the form – [(val1, 'Label1'), (val2, 'Label2'), ...].
  • userGetValTextFuncName

    The name of the custom JS function which you want to use to convert value to label.

    In heavy_data.js, django_select2.getValText() employs the following logic to convert value to label :-

    1. First check if the Select2 input field has txt attribute set along with value. If found then use it.

    2. Otherwise, check if user has provided any custom method for this. Then use that. If it returns a label then use it.

    3. Otherwise, check the cached results. When the user searches in the fields then all the returned responses from server, which has the value and label mapping, are cached by heavy_data.js.

    4. If we still do not have the label then check the cookies. When user selects some value then heavy_data.js stores the selected values and their labels in the cookies. These are cleared when browser is closed.

render_texts(selected_choices, choices)[source]

Renders a JS array with labels for the selected_choices.

Parameters:
  • selected_choices (list or tuple) – List of selected choices’ values.
  • choices (list or tuple) – Extra choices, if any. This is a list of tuples. In each tuple, the first item is the choice value and the second item is choice label.
Returns:

The rendered JS array code.

Return type:

unicode

render_texts_for_value(id_, value, choices)[source]

Renders the JS code which sets the txt attribute on the field. It gets the array of lables from render_texts().

Parameters:
  • id (str) – Id of the field. This can be used to get reference of this field’s DOM in JS.
  • value (Any) – Currently set value on the field.
  • choices (list or tuple) – Extra choices, if any. This is a list of tuples. In each tuple, the first item is the choice value and the second item is choice label.
Returns:

JS code which sets the txt attribute.

Return type:

unicode

class django_select2.widgets.HeavySelect2Widget(**kwargs)[source]

Bases: django_select2.widgets.HeavySelect2Mixin, django.forms.widgets.TextInput

Single selection heavy widget.

Following Select2 option from Select2Mixin.options is added or set:-

  • multiple: False
class django_select2.widgets.HeavySelect2MultipleWidget(**kwargs)[source]

Bases: django_select2.widgets.HeavySelect2Mixin, django_select2.widgets.MultipleSelect2HiddenInput

Multiple selection heavy widget.

Following Select2 options from Select2Mixin.options are removed:-

  • allowClear
  • minimumResultsForSearch

Following Select2 options from Select2Mixin.options are added or set:-

  • multiple: False
  • separator: JSVar('django_select2.MULTISEPARATOR')
render_texts_for_value(id_, value, choices)[source]

Renders the JS code which sets the txt attribute on the field. It gets the array of lables from render_texts().

Parameters:
  • id (str) – Id of the field. This can be used to get reference of this field’s DOM in JS.
  • value (list) – List of currently set value on the field.
  • choices (list or tuple) – Extra choices, if any. This is a list of tuples. In each tuple, the first item is the choice value and the second item is choice label.
Returns:

JS code which sets the txt attribute.

Return type:

unicode

class django_select2.widgets.AutoHeavySelect2Mixin[source]

Bases: object

This mixin is needed for Auto heavy fields.

This mxin adds extra JS code to notify the field’s DOM object of the generated id. The generated id is not the same as the id attribute of the field’s Html markup. This id is generated by register_field() when the Auto field is registered. The client side (DOM) sends this id along with the Ajax request, so that the central view can identify which field should be used to serve the request.

class django_select2.widgets.AutoHeavySelect2Widget(**kwargs)[source]

Bases: django_select2.widgets.AutoHeavySelect2Mixin, django_select2.widgets.HeavySelect2Widget

Auto version of HeavySelect2Widget

class django_select2.widgets.AutoHeavySelect2MultipleWidget(**kwargs)[source]

Bases: django_select2.widgets.AutoHeavySelect2Mixin, django_select2.widgets.HeavySelect2MultipleWidget

Auto version of HeavySelect2MultipleWidget

Table Of Contents

Previous topic

API Reference

Next topic

Fields

This Page