django-select2/django_select2/forms.py

564 lines
18 KiB
Python
Raw Normal View History

2015-09-25 20:11:50 +00:00
"""
Django-Select2 Widgets.
These components are responsible for rendering
the necessary HTML data markups. Since this whole
package is to render choices using Select2 JavaScript
library, hence these components are meant to be used
with choice fields.
Widgets are generally of two types:
1. **Light** --
They are not meant to be used when there
are too many options, say, in thousands.
This is because all those options would
have to be pre-rendered onto the page
and JavaScript would be used to search
through them. Said that, they are also one
the most easiest to use. They are a
drop-in-replacement for Django's default
select widgets.
2. **Heavy** --
They are suited for scenarios when the number of options
are large and need complex queries (from maybe different
sources) to get the options.
This dynamic fetching of options undoubtedly requires
Ajax communication with the server. Django-Select2 includes
a helper JS file which is included automatically,
so you need not worry about writing any Ajax related JS code.
Although on the server side you do need to create a view
specifically to respond to the queries.
3. **Model** --
Model-widgets are a further specialized versions of Heavies.
These do not require views to serve Ajax requests.
When they are instantiated, they register themselves
with one central view which handles Ajax requests for them.
Heavy widgets have the word 'Heavy' in their name.
Light widgets are normally named, i.e. there is no
'Light' word in their names.
.. inheritance-diagram:: django_select2.forms
:parts: 1
"""
from functools import reduce
from itertools import chain
2018-05-07 16:51:21 +00:00
from pickle import PicklingError # nosec
from django import forms
from django.core import signing
2015-08-06 09:58:27 +00:00
from django.db.models import Q
2015-09-15 22:04:33 +00:00
from django.forms.models import ModelChoiceIterator
2017-11-25 16:09:31 +00:00
from django.urls import reverse
2017-07-16 09:19:54 +00:00
from django.utils.translation import get_language
from .cache import cache
from .conf import settings
class Select2Mixin(object):
"""
The base mixin of all Select2 widgets.
2015-08-06 09:58:27 +00:00
This mixin is responsible for rendering the necessary
2015-09-06 03:23:24 +00:00
data attributes for select2 as well as adding the static
form media.
"""
def build_attrs(self, *args, **kwargs):
2015-09-25 20:11:50 +00:00
"""Add select2 data attributes."""
attrs = super(Select2Mixin, self).build_attrs(*args, **kwargs)
2015-09-15 22:04:33 +00:00
if self.is_required:
attrs.setdefault('data-allow-clear', 'false')
else:
attrs.setdefault('data-allow-clear', 'true')
attrs.setdefault('data-placeholder', '')
2015-09-16 09:02:44 +00:00
attrs.setdefault('data-minimum-input-length', 0)
2015-09-06 03:23:24 +00:00
if 'class' in attrs:
attrs['class'] += ' django-select2'
else:
attrs['class'] = 'django-select2'
return attrs
def optgroups(self, name, value, attrs=None):
"""Add empty option for clearable selects."""
if not self.is_required and not self.allow_multiple_selected:
self.choices = list(chain([('', '')], self.choices))
return super(Select2Mixin, self).optgroups(name, value, attrs=attrs)
Made widget media a dynamic property Symptoms: While using AutoModelSelect2Field in admin site, I noticed that css files are rendered only at the first request to the add or edit forms, after that the widget is rendered but without loading any css files from get_select2_css_libs. Solution: I changed assets loading from Assets as a static definition to Media as a dynamic property as described at Django docs: https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property Closed #179 Squashed commit of the following: commit f925ed4a118687b82b6f61d21a9104ccf00859c8 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:39:47 2015 +0300 remove trailing whitespace from docstrings commit b3f6553e422e19c8e065e026511c4ffd91ffee42 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:35:15 2015 +0300 Remove blank lines from docstrings commit 4490b78572a25069472933c88ebee48445b59972 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:19:38 2015 +0300 construct Media the right way Remove code that access private attributes of Media class. commit 6697cd734daca62ff099be73d0685ce6af32e53d Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:11:29 2015 +0300 fix change _media to _get_media I hope it is the final commit :) commit 59bda01aed44e5658825a1bfe37ad09c5760a3ad Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:09:35 2015 +0300 get_select2_heavy_js_libs change get_select2_js_libs to get_select2_heavy_js_libs commit 993e201355c9d5a6012e6f67cfa64462576c2570 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:07:57 2015 +0300 fix fix commit f66e5f40b9f4df295bc5aaa7f2aafe588b2c41bb Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:55:53 2015 +0300 fix fix commit d33d90278345bc32e80e20bdf782fd9ac5eb1800 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:47:25 2015 +0300 fix fix commit f6d956149d2e99ee504c7b2c110f959f7472a181 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:45:09 2015 +0300 fix fix commit 6d737a78cc07507c5b9b91736f6662b5f6f31c57 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:40:01 2015 +0300 global name 'Media' is not defined global name 'Media' is not defined commit 661a817b092dc72bfa8df1a5458d474599c0a50e Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:27:27 2015 +0300 Media as a dynamic property **Symptoms:** While using AutoModelSelect2Field in admin site, I noticed that css files are rendered only at the first request to the add or edit forms, after that the widget is rendered but without loading any css files from get_select2_css_libs. **Solution:** I changed assets loading from [Assets as a static definition](https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property) to [Media as a dynamic property](https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property) as described at Django docs.
2015-06-19 12:49:51 +00:00
def _get_media(self):
"""
2015-08-06 09:58:27 +00:00
Construct Media as a dynamic property.
Made widget media a dynamic property Symptoms: While using AutoModelSelect2Field in admin site, I noticed that css files are rendered only at the first request to the add or edit forms, after that the widget is rendered but without loading any css files from get_select2_css_libs. Solution: I changed assets loading from Assets as a static definition to Media as a dynamic property as described at Django docs: https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property Closed #179 Squashed commit of the following: commit f925ed4a118687b82b6f61d21a9104ccf00859c8 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:39:47 2015 +0300 remove trailing whitespace from docstrings commit b3f6553e422e19c8e065e026511c4ffd91ffee42 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:35:15 2015 +0300 Remove blank lines from docstrings commit 4490b78572a25069472933c88ebee48445b59972 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:19:38 2015 +0300 construct Media the right way Remove code that access private attributes of Media class. commit 6697cd734daca62ff099be73d0685ce6af32e53d Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:11:29 2015 +0300 fix change _media to _get_media I hope it is the final commit :) commit 59bda01aed44e5658825a1bfe37ad09c5760a3ad Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:09:35 2015 +0300 get_select2_heavy_js_libs change get_select2_js_libs to get_select2_heavy_js_libs commit 993e201355c9d5a6012e6f67cfa64462576c2570 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:07:57 2015 +0300 fix fix commit f66e5f40b9f4df295bc5aaa7f2aafe588b2c41bb Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:55:53 2015 +0300 fix fix commit d33d90278345bc32e80e20bdf782fd9ac5eb1800 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:47:25 2015 +0300 fix fix commit f6d956149d2e99ee504c7b2c110f959f7472a181 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:45:09 2015 +0300 fix fix commit 6d737a78cc07507c5b9b91736f6662b5f6f31c57 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:40:01 2015 +0300 global name 'Media' is not defined global name 'Media' is not defined commit 661a817b092dc72bfa8df1a5458d474599c0a50e Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:27:27 2015 +0300 Media as a dynamic property **Symptoms:** While using AutoModelSelect2Field in admin site, I noticed that css files are rendered only at the first request to the add or edit forms, after that the widget is rendered but without loading any css files from get_select2_css_libs. **Solution:** I changed assets loading from [Assets as a static definition](https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property) to [Media as a dynamic property](https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property) as described at Django docs.
2015-06-19 12:49:51 +00:00
2015-09-25 20:11:50 +00:00
.. Note:: For more information visit
https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
Made widget media a dynamic property Symptoms: While using AutoModelSelect2Field in admin site, I noticed that css files are rendered only at the first request to the add or edit forms, after that the widget is rendered but without loading any css files from get_select2_css_libs. Solution: I changed assets loading from Assets as a static definition to Media as a dynamic property as described at Django docs: https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property Closed #179 Squashed commit of the following: commit f925ed4a118687b82b6f61d21a9104ccf00859c8 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:39:47 2015 +0300 remove trailing whitespace from docstrings commit b3f6553e422e19c8e065e026511c4ffd91ffee42 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:35:15 2015 +0300 Remove blank lines from docstrings commit 4490b78572a25069472933c88ebee48445b59972 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:19:38 2015 +0300 construct Media the right way Remove code that access private attributes of Media class. commit 6697cd734daca62ff099be73d0685ce6af32e53d Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:11:29 2015 +0300 fix change _media to _get_media I hope it is the final commit :) commit 59bda01aed44e5658825a1bfe37ad09c5760a3ad Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:09:35 2015 +0300 get_select2_heavy_js_libs change get_select2_js_libs to get_select2_heavy_js_libs commit 993e201355c9d5a6012e6f67cfa64462576c2570 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:07:57 2015 +0300 fix fix commit f66e5f40b9f4df295bc5aaa7f2aafe588b2c41bb Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:55:53 2015 +0300 fix fix commit d33d90278345bc32e80e20bdf782fd9ac5eb1800 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:47:25 2015 +0300 fix fix commit f6d956149d2e99ee504c7b2c110f959f7472a181 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:45:09 2015 +0300 fix fix commit 6d737a78cc07507c5b9b91736f6662b5f6f31c57 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:40:01 2015 +0300 global name 'Media' is not defined global name 'Media' is not defined commit 661a817b092dc72bfa8df1a5458d474599c0a50e Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:27:27 2015 +0300 Media as a dynamic property **Symptoms:** While using AutoModelSelect2Field in admin site, I noticed that css files are rendered only at the first request to the add or edit forms, after that the widget is rendered but without loading any css files from get_select2_css_libs. **Solution:** I changed assets loading from [Assets as a static definition](https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property) to [Media as a dynamic property](https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property) as described at Django docs.
2015-06-19 12:49:51 +00:00
"""
lang = get_language()
i18n_name = None
select2_js = (settings.SELECT2_JS,) if settings.SELECT2_JS else ()
select2_css = (settings.SELECT2_CSS,) if settings.SELECT2_CSS else ()
try:
from django.contrib.admin.widgets import SELECT2_TRANSLATIONS
i18n_name = SELECT2_TRANSLATIONS.get(lang)
if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
i18n_name = None
except ImportError:
# TODO: select2 widget feature needs to be backported into Django 1.11
try:
i = [x.lower() for x in settings.SELECT2_I18N_AVAILABLE_LANGUAGES].index(lang)
i18n_name = settings.SELECT2_I18N_AVAILABLE_LANGUAGES[i]
except ValueError:
pass
i18n_file = ('%s/%s.js' % (settings.SELECT2_I18N_PATH, i18n_name),) if i18n_name else ()
2015-08-06 09:58:27 +00:00
return forms.Media(
js=select2_js + i18n_file + ('django_select2/django_select2.js',),
css={'screen': select2_css}
2015-08-06 09:58:27 +00:00
)
2015-09-06 03:23:24 +00:00
Made widget media a dynamic property Symptoms: While using AutoModelSelect2Field in admin site, I noticed that css files are rendered only at the first request to the add or edit forms, after that the widget is rendered but without loading any css files from get_select2_css_libs. Solution: I changed assets loading from Assets as a static definition to Media as a dynamic property as described at Django docs: https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property Closed #179 Squashed commit of the following: commit f925ed4a118687b82b6f61d21a9104ccf00859c8 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:39:47 2015 +0300 remove trailing whitespace from docstrings commit b3f6553e422e19c8e065e026511c4ffd91ffee42 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:35:15 2015 +0300 Remove blank lines from docstrings commit 4490b78572a25069472933c88ebee48445b59972 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Fri Jun 19 01:19:38 2015 +0300 construct Media the right way Remove code that access private attributes of Media class. commit 6697cd734daca62ff099be73d0685ce6af32e53d Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:11:29 2015 +0300 fix change _media to _get_media I hope it is the final commit :) commit 59bda01aed44e5658825a1bfe37ad09c5760a3ad Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:09:35 2015 +0300 get_select2_heavy_js_libs change get_select2_js_libs to get_select2_heavy_js_libs commit 993e201355c9d5a6012e6f67cfa64462576c2570 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Tue Jun 16 00:07:57 2015 +0300 fix fix commit f66e5f40b9f4df295bc5aaa7f2aafe588b2c41bb Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:55:53 2015 +0300 fix fix commit d33d90278345bc32e80e20bdf782fd9ac5eb1800 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:47:25 2015 +0300 fix fix commit f6d956149d2e99ee504c7b2c110f959f7472a181 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:45:09 2015 +0300 fix fix commit 6d737a78cc07507c5b9b91736f6662b5f6f31c57 Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:40:01 2015 +0300 global name 'Media' is not defined global name 'Media' is not defined commit 661a817b092dc72bfa8df1a5458d474599c0a50e Author: Razi Alsayyed <razi.sayed@gmail.com> Date: Mon Jun 15 23:27:27 2015 +0300 Media as a dynamic property **Symptoms:** While using AutoModelSelect2Field in admin site, I noticed that css files are rendered only at the first request to the add or edit forms, after that the widget is rendered but without loading any css files from get_select2_css_libs. **Solution:** I changed assets loading from [Assets as a static definition](https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property) to [Media as a dynamic property](https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property) as described at Django docs.
2015-06-19 12:49:51 +00:00
media = property(_get_media)
class Select2TagMixin(object):
"""Mixin to add select2 tag functionality."""
def build_attrs(self, *args, **kwargs):
"""Add select2's tag attributes."""
self.attrs.setdefault('data-minimum-input-length', 1)
self.attrs.setdefault('data-tags', 'true')
self.attrs.setdefault('data-token-separators', '[",", " "]')
return super(Select2TagMixin, self).build_attrs(*args, **kwargs)
class Select2Widget(Select2Mixin, forms.Select):
2015-09-25 20:11:50 +00:00
"""
Select2 drop in widget.
Example usage::
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('my_field', )
widgets = {
'my_field': Select2Widget
}
or::
class MyForm(forms.Form):
my_choice = forms.ChoiceField(widget=Select2Widget)
"""
2015-09-06 03:23:24 +00:00
pass
2015-08-06 09:58:27 +00:00
2015-09-06 03:23:24 +00:00
class Select2MultipleWidget(Select2Mixin, forms.SelectMultiple):
2015-09-25 20:11:50 +00:00
"""
Select2 drop in widget for multiple select.
Works just like :class:`.Select2Widget` but for multi select.
"""
2015-09-06 03:23:24 +00:00
pass
class Select2TagWidget(Select2TagMixin, Select2Mixin, forms.SelectMultiple):
"""
Select2 drop in widget for for tagging.
Example for :class:`.django.contrib.postgres.fields.ArrayField`::
class MyWidget(Select2TagWidget):
def value_from_datadict(self, data, files, name):
values = super(MyWidget, self).value_from_datadict(data, files, name):
return ",".join(values)
def optgroups(self, name, value, attrs=None):
values = value[0].split(',') if value[0] else []
selected = set(values)
subgroup = [self.create_option(name, v, v, selected, i) for i, v in enumerate(values)]
return [(None, subgroup, 0)]
"""
pass
2016-02-04 10:45:44 +00:00
class HeavySelect2Mixin(object):
"""Mixin that adds select2's AJAX options and registers itself on Django's cache."""
2017-04-11 11:28:39 +00:00
dependent_fields = {}
def __init__(self, attrs=None, choices=(), **kwargs):
2015-09-25 20:11:50 +00:00
"""
Return HeavySelect2Mixin.
Args:
data_view (str): URL pattern name
data_url (str): URL
2017-04-11 11:28:39 +00:00
dependent_fields (dict): Dictionary of dependent parent fields.
The value of the dependent field will be passed as to :func:`.filter_queryset`.
It can be used to further restrict the search results. For example, a city
widget could be dependent on a country.
Key is a name of a field in a form.
Value is a name of a field in a model (used in `queryset`).
2015-09-25 20:11:50 +00:00
"""
self.choices = choices
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
2015-09-15 22:04:33 +00:00
self.data_view = kwargs.pop('data_view', None)
self.data_url = kwargs.pop('data_url', None)
2017-04-11 11:28:39 +00:00
dependent_fields = kwargs.pop('dependent_fields', None)
if dependent_fields is not None:
self.dependent_fields = dict(dependent_fields)
2015-09-15 22:04:33 +00:00
if not (self.data_view or self.data_url):
2015-09-16 09:02:44 +00:00
raise ValueError('You must ether specify "data_view" or "data_url".')
2015-09-06 03:23:24 +00:00
self.userGetValTextFuncName = kwargs.pop('userGetValTextFuncName', 'null')
2015-09-06 03:23:24 +00:00
def get_url(self):
"""Return URL from instance or by reversing :attr:`.data_view`."""
2015-09-15 22:04:33 +00:00
if self.data_url:
return self.data_url
2016-01-27 08:59:49 +00:00
return reverse(self.data_view)
def build_attrs(self, *args, **kwargs):
"""Set select2's AJAX attributes."""
attrs = super(HeavySelect2Mixin, self).build_attrs(*args, **kwargs)
2015-08-06 09:58:27 +00:00
2015-09-06 03:23:24 +00:00
# encrypt instance Id
2015-09-16 09:02:44 +00:00
self.widget_id = signing.dumps(id(self))
2015-09-16 09:02:44 +00:00
attrs['data-field_id'] = self.widget_id
2015-09-06 03:23:24 +00:00
attrs.setdefault('data-ajax--url', self.get_url())
attrs.setdefault('data-ajax--cache', "true")
attrs.setdefault('data-ajax--type', "GET")
2015-09-16 09:02:44 +00:00
attrs.setdefault('data-minimum-input-length', 2)
2017-04-11 11:28:39 +00:00
if self.dependent_fields:
attrs.setdefault('data-select2-dependent-fields', " ".join(self.dependent_fields))
2015-09-15 22:04:33 +00:00
2015-09-16 09:02:44 +00:00
attrs['class'] += ' django-select2-heavy'
2015-09-06 03:23:24 +00:00
return attrs
def render(self, *args, **kwargs):
2015-09-25 20:11:50 +00:00
"""Render widget and register it in Django's cache."""
output = super(HeavySelect2Mixin, self).render(*args, **kwargs)
2015-09-16 09:02:44 +00:00
self.set_to_cache()
return output
2015-09-06 03:23:24 +00:00
def _get_cache_key(self):
return "%s%s" % (settings.SELECT2_CACHE_PREFIX, id(self))
2015-09-16 09:02:44 +00:00
def set_to_cache(self):
"""
Add widget object to Django's cache.
You may need to overwrite this method, to pickle all information
that is required to serve your JSON response view.
"""
try:
cache.set(self._get_cache_key(), {
'widget': self,
'url': self.get_url(),
})
2017-11-25 16:23:36 +00:00
except (PicklingError, AttributeError):
msg = "You need to overwrite \"set_to_cache\" or ensure that %s is serialisable."
raise NotImplementedError(msg % self.__class__.__name__)
2016-02-04 10:45:44 +00:00
class HeavySelect2Widget(HeavySelect2Mixin, Select2Widget):
2015-09-25 20:11:50 +00:00
"""
Select2 widget with AJAX support that registers itself to Django's Cache.
Usage example::
2016-04-03 11:20:53 +00:00
class MyWidget(HeavySelect2Widget):
2015-09-25 20:11:50 +00:00
data_view = 'my_view_name'
or::
class MyForm(forms.Form):
my_field = forms.ChoiceField(
2016-04-03 11:20:53 +00:00
widget=HeavySelect2Widget(
2015-09-25 20:11:50 +00:00
data_url='/url/to/json/response'
)
)
"""
2015-09-06 03:23:24 +00:00
pass
2016-02-04 10:45:44 +00:00
class HeavySelect2MultipleWidget(HeavySelect2Mixin, Select2MultipleWidget):
2015-09-25 20:11:50 +00:00
"""Select2 multi select widget similar to :class:`.HeavySelect2Widget`."""
2015-09-06 03:23:24 +00:00
pass
2015-08-06 09:58:27 +00:00
2016-02-04 10:45:44 +00:00
class HeavySelect2TagWidget(HeavySelect2Mixin, Select2TagWidget):
2015-11-29 19:47:22 +00:00
"""Select2 tag widget."""
pass
2015-08-06 09:58:27 +00:00
2015-09-06 03:23:24 +00:00
# Auto Heavy widgets
2015-09-06 03:23:24 +00:00
class ModelSelect2Mixin(object):
2015-09-25 20:11:50 +00:00
"""Widget mixin that provides attributes and methods for :class:`.AutoResponseView`."""
model = None
queryset = None
search_fields = []
2015-09-25 20:11:50 +00:00
"""
Model lookups that are used to filter the QuerySet.
2015-09-25 20:11:50 +00:00
Example::
search_fields = [
'title__icontains',
]
"""
max_results = 25
2015-09-25 20:11:50 +00:00
"""Maximal results returned by :class:`.AutoResponseView`."""
2015-09-06 03:23:24 +00:00
def __init__(self, *args, **kwargs):
2015-09-25 20:11:50 +00:00
"""
Overwrite class parameters if passed as keyword arguments.
Args:
model (django.db.models.Model): Model to select choices from.
2017-04-11 11:28:39 +00:00
queryset (django.db.models.query.QuerySet): QuerySet to select choices from.
search_fields (list): List of model lookup strings.
max_results (int): Max. JsonResponse view page size.
2015-09-25 20:11:50 +00:00
"""
self.model = kwargs.pop('model', self.model)
self.queryset = kwargs.pop('queryset', self.queryset)
self.search_fields = kwargs.pop('search_fields', self.search_fields)
self.max_results = kwargs.pop('max_results', self.max_results)
2015-09-15 22:04:33 +00:00
defaults = {'data_view': 'django_select2-json'}
2015-09-06 03:23:24 +00:00
defaults.update(kwargs)
super(ModelSelect2Mixin, self).__init__(*args, **defaults)
def set_to_cache(self):
"""
Add widget's attributes to Django's cache.
Split the QuerySet, to not pickle the result set.
"""
queryset = self.get_queryset()
cache.set(self._get_cache_key(), {
'queryset':
[
queryset.none(),
queryset.query,
],
'cls': self.__class__,
'search_fields': self.search_fields,
'max_results': self.max_results,
'url': self.get_url(),
2017-04-11 11:28:39 +00:00
'dependent_fields': self.dependent_fields,
})
2017-04-11 11:28:39 +00:00
def filter_queryset(self, term, queryset=None, **dependent_fields):
2015-09-25 20:11:50 +00:00
"""
Return QuerySet filtered by search_fields matching the passed term.
Args:
term (str): Search term
2017-04-11 11:28:39 +00:00
queryset (django.db.models.query.QuerySet): QuerySet to select choices from.
**dependent_fields: Dependent fields and their values. If you want to inherit
from ModelSelect2Mixin and later call to this method, be sure to pop
everything from keyword arguments that is not a dependent field.
Returns:
QuerySet: Filtered QuerySet
2015-09-25 20:11:50 +00:00
"""
if queryset is None:
queryset = self.get_queryset()
search_fields = self.get_search_fields()
2015-10-01 10:21:35 +00:00
select = Q()
term = term.replace('\t', ' ')
term = term.replace('\n', ' ')
for t in [t for t in term.split(' ') if not t == '']:
select &= reduce(lambda x, y: x | Q(**{y: t}), search_fields,
Q(**{search_fields[0]: t}))
2017-04-11 11:28:39 +00:00
if dependent_fields:
select &= Q(**dependent_fields)
return queryset.filter(select).distinct()
def get_queryset(self):
2015-09-25 20:11:50 +00:00
"""
Return QuerySet based on :attr:`.queryset` or :attr:`.model`.
Returns:
QuerySet: QuerySet of available choices.
2015-09-25 20:11:50 +00:00
"""
if self.queryset is not None:
queryset = self.queryset
elif self.model is not None:
queryset = self.model._default_manager.all()
else:
raise NotImplementedError(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
"%(cls)s.get_queryset()." % {
'cls': self.__class__.__name__
}
)
return queryset
def get_search_fields(self):
2015-09-25 20:11:50 +00:00
"""Return list of lookup names."""
if self.search_fields:
return self.search_fields
raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__)
def optgroups(self, name, value, attrs=None):
"""Return only selected options and set QuerySet from `ModelChoicesIterator`."""
default = (None, [], 0)
groups = [default]
has_selected = False
2017-11-25 16:23:36 +00:00
selected_choices = {str(v) for v in value}
if not self.is_required and not self.allow_multiple_selected:
default[1].append(self.create_option(name, '', '', False, 0))
if not isinstance(self.choices, ModelChoiceIterator):
return super(ModelSelect2Mixin, self).optgroups(name, value, attrs=attrs)
selected_choices = {
c for c in selected_choices
if c not in self.choices.field.empty_values
}
field_name = self.choices.field.to_field_name or 'pk'
query = Q(**{'%s__in' % field_name: selected_choices})
for obj in self.choices.queryset.filter(query):
option_value = self.choices.choice(obj)[0]
option_label = self.label_from_instance(obj)
selected = (
2017-11-25 16:23:36 +00:00
str(option_value) in value and
(has_selected is False or self.allow_multiple_selected)
)
if selected is True and has_selected is False:
has_selected = True
index = len(default[1])
subgroup = default[1]
subgroup.append(self.create_option(name, option_value, option_label, selected_choices, index))
return groups
def label_from_instance(self, obj):
"""
Return option label representation from instance.
Can be overridden to change the representation of each choice.
Example usage::
class MyWidget(ModelSelect2Widget):
def label_from_instance(obj):
2017-11-25 16:23:36 +00:00
return str(obj.title).upper()
Args:
obj (django.db.models.Model): Instance of Django Model.
Returns:
str: Option label.
"""
2017-11-25 16:23:36 +00:00
return str(obj)
2015-09-06 03:23:24 +00:00
class ModelSelect2Widget(ModelSelect2Mixin, HeavySelect2Widget):
2015-09-25 20:11:50 +00:00
"""
Select2 drop in model select widget.
Example usage::
class MyWidget(ModelSelect2Widget):
search_fields = [
2015-11-27 18:06:32 +00:00
'title__icontains',
2015-09-25 20:11:50 +00:00
]
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('my_field', )
widgets = {
'my_field': MyWidget,
}
or::
class MyForm(forms.Form):
my_choice = forms.ChoiceField(
widget=ModelSelect2Widget(
model=MyOtherModel,
search_fields=['title__icontains']
)
)
.. tip:: The ModelSelect2(Multiple)Widget will try
to get the QuerySet from the fields choices.
Therefore you don't need to define a QuerySet,
2015-09-25 20:11:50 +00:00
if you just drop in the widget for a ForeignKey field.
"""
2015-08-06 09:58:27 +00:00
pass
2015-09-06 03:23:24 +00:00
class ModelSelect2MultipleWidget(ModelSelect2Mixin, HeavySelect2MultipleWidget):
2015-09-25 20:11:50 +00:00
"""
Select2 drop in model multiple select widget.
Works just like :class:`.ModelSelect2Widget` but for multi select.
"""
2015-08-06 09:58:27 +00:00
pass
2016-02-04 10:45:44 +00:00
class ModelSelect2TagWidget(ModelSelect2Mixin, HeavySelect2TagWidget):
2015-09-25 20:11:50 +00:00
"""
2015-11-29 19:47:22 +00:00
Select2 model widget with tag support.
2015-09-25 20:11:50 +00:00
This it not a simple drop in widget.
It requires to implement you own :func:`.value_from_datadict`
that adds missing tags to you QuerySet.
2015-09-25 20:11:50 +00:00
Example::
class MyModelSelect2TagWidget(ModelSelect2TagWidget):
queryset = MyModel.objects.all()
def value_from_datadict(self, data, files, name):
values = super().value_from_datadict(self, data, files, name)
qs = self.queryset.filter(**{'pk__in': list(values)})
2017-11-25 16:23:36 +00:00
pks = set(str(getattr(o, pk)) for o in qs)
2015-09-25 20:11:50 +00:00
cleaned_values = []
for val in value:
2017-11-25 16:23:36 +00:00
if str(val) not in pks:
2015-09-25 20:11:50 +00:00
val = queryset.create(title=val).pk
cleaned_values.append(val)
return cleaned_values
"""
2015-08-06 09:58:27 +00:00
pass