Fields

Class Diagrams

Inheritance diagram of django_select2.fields.Select2ChoiceField, django_select2.fields.Select2MultipleChoiceField

Inheritance diagram of django_select2.fields.ModelSelect2Field, django_select2.fields.ModelSelect2MultipleField

Inheritance diagram of django_select2.fields.HeavySelect2TagField

Inheritance diagram of django_select2.fields.HeavyModelSelect2ChoiceField, django_select2.fields.HeavyModelSelect2MultipleChoiceField, django_select2.fields.HeavyModelSelect2TagField

Inheritance diagram of django_select2.fields.AutoSelect2Field, django_select2.fields.AutoSelect2MultipleField, django_select2.fields.AutoSelect2TagField

Inheritance diagram of django_select2.fields.AutoModelSelect2Field

Inheritance diagram of django_select2.fields.AutoModelSelect2MultipleField, django_select2.fields.AutoModelSelect2TagField

Reference

Contains all the Django fields for Select2.

class django_select2.fields.AutoViewFieldMixin(*args, **kwargs)[source]

Bases: object

Registers itself with AutoResponseView.

All Auto fields must sub-class this mixin, so that they are registered.

Warning

Do not forget to include 'django_select2.urls' in your url conf, else, central view used to serve Auto fields won’t be available.

__init__(*args, **kwargs)[source]

Class constructor.

Parameters:auto_id (unicode) –

The key to use while registering this field. If it is not provided then an auto generated key is used.

Tip

This mixin uses full class name of the field to register itself. This is used like key in a dict by util.register_field().

If that key already exists then the instance is not registered again. So, eventually all instances of an Auto field share one instance to respond to the Ajax queries for its fields.

If for some reason any instance needs to be isolated then auto_id can be used to provide a unique key which has never occured before.

security_check(request, *args, **kwargs)[source]

Returns False if security check fails.

Parameters:
Returns:

A boolean value, signalling if check passed or failed.

Return type:

bool

Warning

Sub-classes should override this. You really do not want random people making Http requests to your server, be able to get access to sensitive information.

get_results(request, term, page, context)[source]

See views.Select2View.get_results().

class django_select2.fields.Select2ChoiceField(choices=(), required=True, widget=None, label=None, initial=None, help_text=u'', *args, **kwargs)[source]

Bases: django.forms.fields.ChoiceField

Drop-in Select2 replacement for forms.ChoiceField.

widget

alias of Select2Widget

class django_select2.fields.Select2MultipleChoiceField(choices=(), required=True, widget=None, label=None, initial=None, help_text=u'', *args, **kwargs)[source]

Bases: django.forms.fields.MultipleChoiceField

Drop-in Select2 replacement for forms.MultipleChoiceField.

widget

alias of Select2MultipleWidget

class django_select2.fields.ModelResultJsonMixin(*args, **kwargs)[source]

Bases: object

Makes heavy_data.js parsable JSON response for queries on its model.

On query it uses prepare_qs_params() to prepare query attributes which it then passes to self.queryset.filter() to get the results.

It is expected that sub-classes will defined a class field variable search_fields, which should be a list of field names to search for.

Note

As of version 3.1.3, search_fields is optional if sub-class overrides get_results.

__init__(*args, **kwargs)[source]

Class constructor.

Parameters:
  • queryset (django.db.models.query.QuerySet or None) – This can be passed as kwarg here or defined as field variable, like search_fields.
  • max_results (int) – Maximum number to results to return per Ajax query.
  • to_field_name (str) – Which field’s value should be returned as result tuple’s value. (Default is pk, i.e. the id field of the model)
get_queryset()[source]

Returns the queryset.

The default implementation returns the self.queryset, which is usually the one set by sub-classes at class-level. However, if that is None then ValueError is thrown.

Returns:queryset
Return type:django.db.models.query.QuerySet
label_from_instance(obj)[source]

Sub-classes should override this to generate custom label texts for values.

Parameters:obj (django.model.Model) – The model object.
Returns:The label string.
Return type:unicode
extra_data_from_instance(obj)[source]

Sub-classes should override this to generate extra data for values. These are passed to JavaScript and can be used for custom rendering.

Parameters:obj (django.model.Model) – The model object.
Returns:The extra data dictionary.
Return type:dict
prepare_qs_params(request, search_term, search_fields)[source]

Prepares queryset parameter to use for searching.

Parameters:
  • search_term (list) – The search term.
  • search_fields – The list of search fields. This is same as self.search_fields.
Returns:

A dictionary of parameters to ‘or’ and ‘and’ together. The output format should be

{
    'or': [
    Q(attr11=term11) | Q(attr12=term12) | ...,
    Q(attrN1=termN1) | Q(attrN2=termN2) | ...,
    ...],

    'and': {
        'attrX1': termX1,
        'attrX2': termX2,
        ...
    }
}

The above would then be coaxed into filter() as below:

queryset.filter(
    Q(attr11=term11) | Q(attr12=term12) | ...,
    Q(attrN1=termN1) | Q(attrN2=termN2) | ...,
    ...,
    attrX1=termX1,
    attrX2=termX2,
    ...
    )

In this implementation, term11, term12, termN1, ... etc., all are actually search_term. Also then and part is always empty.

So, let’s take an example.

Assume, search_term == 'John'
self.search_fields == ['first_name__icontains', 'last_name__icontains']

So, the prepared query would be:

{
    'or': [
        Q(first_name__icontains=search_term) | Q(last_name__icontains=search_term)
    ],
    'and': {}
}

Return type:

dict

get_results(request, term, page, context)[source]

See views.Select2View.get_results().

This implementation takes care of detecting if more results are available.

class django_select2.fields.UnhideableQuerysetType[source]

Bases: type

This does some pretty nasty hacky stuff, to make sure users can also define queryset as class-level field variable, instead of passing it to constructor.

class django_select2.fields.ChoiceMixin[source]

Bases: object

Simple mixin which provides a property – choices. When choices is set, then it sets that value to self.widget.choices too.

class django_select2.fields.FilterableModelChoiceIterator(field)[source]

Bases: django.forms.models.ModelChoiceIterator

Extends ModelChoiceIterator to add the capability to apply additional filter on the passed queryset.

set_extra_filter(**filter_map)[source]

Applies additional filter on the queryset. This can be called multiple times.

Parameters:filter_map – The **kwargs to pass to django.db.models.query.QuerySet.filter(). If this is not set then additional filter (if) applied before is removed.
class django_select2.fields.QuerysetChoiceMixin[source]

Bases: django_select2.fields.ChoiceMixin

Overrides choices‘ getter to return instance of FilterableModelChoiceIterator instead.

class django_select2.fields.ModelSelect2Field(*args, **kwargs)[source]

Bases: django_select2.fields.ModelChoiceField

Light Select2 field, specialized for Models.

Select2 replacement for forms.ModelChoiceField.

widget

alias of Select2Widget

class django_select2.fields.ModelSelect2MultipleField(*args, **kwargs)[source]

Bases: django_select2.fields.ModelMultipleChoiceField

Light multiple-value Select2 field, specialized for Models.

Select2 replacement for forms.ModelMultipleChoiceField.

widget

alias of Select2MultipleWidget

class django_select2.fields.HeavySelect2FieldBaseMixin(*args, **kwargs)[source]

Bases: object

Base mixin field for all Heavy fields.

Note

Although Heavy fields accept choices parameter like all Django choice fields, but these fields are backed by big data sources, so choices cannot possibly have all the values.

For Heavies, consider choices to be a subset of all possible choices. It is available because users might expect it to be available.

__init__(*args, **kwargs)[source]

Class constructor.

Parameters:

Warning

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

class django_select2.fields.HeavyChoiceField(*args, **kwargs)[source]

Bases: django_select2.fields.ChoiceMixin, django.forms.fields.Field

Reimplements django.forms.TypedChoiceField in a way which suites the use of big data.

Note

Although this field accepts choices parameter like all Django choice fields, but these fields are backed by big data sources, so choices cannot possibly have all the values. It is meant to be a subset of all possible choices.

empty_value = u''

Sub-classes can set this other value if needed.

coerce_value(value)[source]

Coerces value to a Python data type.

Sub-classes should override this if they do not want Unicode values.

validate_value(value)[source]

Sub-classes can override this to validate the value entered against the big data.

Parameters:value (As coerced by coerce_value().) – Value entered by the user.
Returns:True means the value is valid.
get_val_txt(value)[source]

If Heavy widgets encounter any value which it can’t find in choices then it calls this method to get the label for the value.

Parameters:value (As coerced by coerce_value().) – Value entered by the user.
Returns:The label for this value.
Return type:unicode or None (when no possible label could be found)
class django_select2.fields.HeavyMultipleChoiceField(*args, **kwargs)[source]

Bases: django_select2.fields.HeavyChoiceField

Reimplements django.forms.TypedMultipleChoiceField in a way which suites the use of big data.

Note

Although this field accepts choices parameter like all Django choice fields, but these fields are backed by big data sources, so choices cannot possibly have all the values. It is meant to be a subset of all possible choices.

hidden_widget

alias of MultipleHiddenInput

class django_select2.fields.HeavySelect2ChoiceField(*args, **kwargs)[source]

Bases: django_select2.fields.HeavySelect2FieldBaseMixin, django_select2.fields.HeavyChoiceField

Heavy Select2 Choice field.

widget

alias of HeavySelect2Widget

class django_select2.fields.HeavySelect2MultipleChoiceField(*args, **kwargs)[source]

Bases: django_select2.fields.HeavySelect2FieldBaseMixin, django_select2.fields.HeavyMultipleChoiceField

Heavy Select2 Multiple Choice field.

widget

alias of HeavySelect2MultipleWidget

class django_select2.fields.HeavySelect2TagField(*args, **kwargs)[source]

Bases: django_select2.fields.HeavySelect2MultipleChoiceField

Heavy Select2 field for tagging.

Warning

NotImplementedError would be thrown if create_new_value() is not implemented.

widget

alias of HeavySelect2TagWidget

create_new_value(value)[source]

This is called when the input value is not valid. This allows you to add the value into the data-store. If that is not done then eventually the validation will fail.

Parameters:value (As coerced by HeavyChoiceField.coerce_value().) – Invalid value entered by the user.
Returns:The a new value, which could be the id (pk) of the created value.
Return type:Any
class django_select2.fields.HeavyModelSelect2ChoiceField(*args, **kwargs)[source]

Bases: django_select2.fields.HeavySelect2FieldBaseMixin, django_select2.fields.ModelChoiceField

Heavy Select2 Choice field, specialized for Models.

widget

alias of HeavySelect2Widget

class django_select2.fields.HeavyModelSelect2MultipleChoiceField(*args, **kwargs)[source]

Bases: django_select2.fields.HeavySelect2FieldBaseMixin, django_select2.fields.ModelMultipleChoiceField

Heavy Select2 Multiple Choice field, specialized for Models.

widget

alias of HeavySelect2MultipleWidget

class django_select2.fields.HeavyModelSelect2TagField(*args, **kwargs)[source]

Bases: django_select2.fields.HeavySelect2FieldBaseMixin, django_select2.fields.ModelMultipleChoiceField

Heavy Select2 field for tagging, specialized for Models.

Warning

NotImplementedError would be thrown if get_model_field_values() is not implemented.

widget

alias of HeavySelect2TagWidget

create_new_value(value)[source]

This is called when the input value is not valid. This allows you to add the value into the data-store. If that is not done then eventually the validation will fail.

Parameters:value (As coerced by HeavyChoiceField.coerce_value().) – Invalid value entered by the user.
Returns:The a new value, which could be the id (pk) of the created value.
Return type:Any
get_model_field_values(value)[source]

This is called when the input value is not valid and the field tries to create a new model instance.

Parameters:value (unicode) – Invalid value entered by the user.
Returns:Dict with attribute name - attribute value pair.
Return type:dict
class django_select2.fields.AutoSelect2Field(*args, **kwargs)[source]

Bases: django_select2.fields.AutoViewFieldMixin, django_select2.fields.HeavySelect2ChoiceField

Auto Heavy Select2 field.

This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming json query requests for that type (class).

Warning

NotImplementedError would be thrown if get_results() is not implemented.

widget

alias of AutoHeavySelect2Widget

class django_select2.fields.AutoSelect2MultipleField(*args, **kwargs)[source]

Bases: django_select2.fields.AutoViewFieldMixin, django_select2.fields.HeavySelect2MultipleChoiceField

Auto Heavy Select2 field for multiple choices.

This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming json query requests for that type (class).

Warning

NotImplementedError would be thrown if get_results() is not implemented.

widget

alias of AutoHeavySelect2MultipleWidget

class django_select2.fields.AutoSelect2TagField(*args, **kwargs)[source]

Bases: django_select2.fields.AutoViewFieldMixin, django_select2.fields.HeavySelect2TagField

Auto Heavy Select2 field for tagging.

This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming json query requests for that type (class).

Warning

NotImplementedError would be thrown if get_results() is not implemented.

widget

alias of AutoHeavySelect2TagWidget

class django_select2.fields.AutoModelSelect2Field(*args, **kwargs)[source]

Bases: django_select2.fields.ModelResultJsonMixin, django_select2.fields.AutoViewFieldMixin, django_select2.fields.HeavyModelSelect2ChoiceField

Auto Heavy Select2 field, specialized for Models.

This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming json query requests for that type (class).

widget

alias of AutoHeavySelect2Widget

class django_select2.fields.AutoModelSelect2MultipleField(*args, **kwargs)[source]

Bases: django_select2.fields.ModelResultJsonMixin, django_select2.fields.AutoViewFieldMixin, django_select2.fields.HeavyModelSelect2MultipleChoiceField

Auto Heavy Select2 field for multiple choices, specialized for Models.

This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming json query requests for that type (class).

widget

alias of AutoHeavySelect2MultipleWidget

class django_select2.fields.AutoModelSelect2TagField(*args, **kwargs)[source]

Bases: django_select2.fields.ModelResultJsonMixin, django_select2.fields.AutoViewFieldMixin, django_select2.fields.HeavyModelSelect2TagField

Auto Heavy Select2 field for tagging, specialized for Models.

This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming json query requests for that type (class).

Warning

NotImplementedError would be thrown if get_model_field_values() is not implemented.

Example:

class Tag(models.Model):
    tag = models.CharField(max_length=10, unique=True)
    def __unicode__(self):
        return unicode(self.tag)

class TagField(AutoModelSelect2TagField):
    queryset = Tag.objects
    search_fields = ['tag__icontains', ]
    def get_model_field_values(self, value):
        return {'tag': value}
widget

alias of AutoHeavySelect2TagWidget