Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f5644b479 | ||
|
|
c797e59584 | ||
|
|
72616f8276 | ||
|
|
99aed19308 | ||
|
|
74bf15ce48 | ||
|
|
57dfd53d55 | ||
|
|
f943fe07f5 | ||
|
|
a6a12d7392 | ||
|
|
f579f4af35 | ||
|
|
0b3abb8f1f | ||
|
|
01c8979100 | ||
|
|
f6ee1f57db | ||
|
|
894a251be3 | ||
|
|
9ed8f58fa6 | ||
|
|
a8a4baf04d | ||
|
|
5b0400dfaa | ||
|
|
7923eeb0ee | ||
|
|
f09f9e5249 | ||
|
|
031ec6682c | ||
|
|
4dacbdf283 | ||
|
|
bc9601b3d3 | ||
|
|
d57b726d34 | ||
|
|
d25e733c85 | ||
|
|
27091f5b49 | ||
|
|
8d48887f5c | ||
|
|
fa6a841746 | ||
|
|
0ee50d9866 | ||
|
|
7d8908daab |
+41
-22
@@ -1,36 +1,55 @@
|
||||
language: python
|
||||
sudo: false
|
||||
cache:
|
||||
- pip
|
||||
- apt
|
||||
- pip
|
||||
services:
|
||||
- memcached
|
||||
- memcached
|
||||
python:
|
||||
- "2.7"
|
||||
- "3.4"
|
||||
- "3.5"
|
||||
- '2.7'
|
||||
- '3.4'
|
||||
- '3.5'
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- python3-enchant
|
||||
- python2-enchant
|
||||
- graphviz
|
||||
env:
|
||||
global:
|
||||
- DISPLAY=:99.0
|
||||
- DISPLAY=:99.0
|
||||
matrix:
|
||||
- DJANGO="Django<1.9,>=1.8"
|
||||
- DJANGO="Django<1.10,>=1.9"
|
||||
- DJANGO="-e git+https://github.com/django/django.git@master#egg=Django"
|
||||
- DJANGO="Django<1.9,>=1.8"
|
||||
- DJANGO="Django<1.10,>=1.9"
|
||||
- DJANGO="-e git+https://github.com/django/django.git@master#egg=Django"
|
||||
matrix:
|
||||
fast_finish: true
|
||||
allow_failures:
|
||||
- env: DJANGO="-e git+https://github.com/django/django.git@master#egg=Django"
|
||||
- env: DJANGO="-e git+https://github.com/django/django.git@master#egg=Django"
|
||||
install:
|
||||
- pip install --upgrade pip
|
||||
- pip install -r requirements_dev.txt
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == 2* ]] || [[ $TRAVIS_PYTHON_VERSION == pypy ]]; then pip install python-memcached; fi
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == 3* ]] || [[ $TRAVIS_PYTHON_VERSION == pypy3 ]]; then pip install python3-memcached; fi
|
||||
- pip install $DJANGO
|
||||
- pip install coveralls
|
||||
- sh -e /etc/init.d/xvfb start
|
||||
- pip install --upgrade pip
|
||||
- pip install -r requirements_dev.txt
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == 2* ]] || [[ $TRAVIS_PYTHON_VERSION == pypy ]]; then
|
||||
pip install python-memcached; fi
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == 3* ]] || [[ $TRAVIS_PYTHON_VERSION == pypy3 ]];
|
||||
then pip install python3-memcached; fi
|
||||
- pip install $DJANGO
|
||||
- pip install coveralls
|
||||
- sh -e /etc/init.d/xvfb start
|
||||
script:
|
||||
- isort --check-only --recursive --diff .
|
||||
- flake8 --jobs=2 .
|
||||
- pep257 --explain --source --count django_select2
|
||||
- coverage run --source=django_select2 -m py.test
|
||||
- isort --check-only --recursive --diff .
|
||||
- flake8 --jobs=2 .
|
||||
- pep257 --explain --source --count django_select2
|
||||
- "(cd docs; make spelling)"
|
||||
- coverage run --source=django_select2 -m py.test
|
||||
after_success:
|
||||
- coveralls
|
||||
- coveralls
|
||||
deploy:
|
||||
provider: pypi
|
||||
user: codingjoe
|
||||
password:
|
||||
secure: fEP9K7y0ZF9fRvQEUN4kgPXQEZvi3Cx3ikUebG2UM/2uhcaUQm0+KpgZ2S+lvOTYcBnNgzPzFsVIZMcVcTxwIKuQDEMq9y2eop2hnisb9KXsIm9qPYSzOnRm74VuiOt4hNOZMe0qVBK2cO3vC9NDXuzdI8A0JynJhthfl4t+kFM=
|
||||
on:
|
||||
tags: true
|
||||
distributions: sdist bdist_wheel
|
||||
repo: applegrew/django-select2
|
||||
|
||||
@@ -1,6 +1,25 @@
|
||||
Changelog Summary
|
||||
=================
|
||||
|
||||
### v5.8.8
|
||||
* Upgrade Select2 to version 4.0.3
|
||||
|
||||
### v5.8.7
|
||||
* Fix #285 -- Do not evaluate queryset in `render_options`.
|
||||
|
||||
### v5.8.3
|
||||
* Remove six dependency -- User django.utils.six instead.
|
||||
|
||||
### v5.8.2
|
||||
* Fixes #260 -- Fixes bug in render choices
|
||||
|
||||
### v5.8.0
|
||||
* Changed signature of `render` and `render_choices` to satisfy Django 1.10 changes.
|
||||
* Changed widgets' inheritance tree to be more consistent.
|
||||
|
||||
### v5.7.1
|
||||
* Fixes pickle bug of lazy object
|
||||
|
||||
### v5.7.0
|
||||
* Security fix that allows a `field_id` to only be used for the intended JSON endpoint.
|
||||
|
||||
|
||||
@@ -3,3 +3,6 @@ recursive-include django_select2/static *.*
|
||||
recursive-exclude django_select2/static .DS_Store
|
||||
exclude requirements_dev.txt
|
||||
prune tests
|
||||
|
||||
[bdist_wheel]
|
||||
universal=1
|
||||
|
||||
@@ -3,7 +3,7 @@ Django-Select2
|
||||
|
||||
[](https://pypi.python.org/pypi/Django-Select2/)
|
||||
[](https://travis-ci.org/applegrew/django-select2)
|
||||
[](https://coveralls.io/r/applegrew/django-select2)
|
||||
[](https://coveralls.io/r/applegrew/django-select2)
|
||||
[](https://raw.githubusercontent.com/applegrew/django-select2/master/LICENSE.txt)
|
||||
[](https://gitter.im/applegrew/django-select2?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
@@ -54,7 +54,7 @@ Major changes:
|
||||
## Documentation
|
||||
|
||||
|
||||
Documentation available at http://django-select2.readthedocs.org/.
|
||||
Documentation available at http://django-select2.readthedocs.io/.
|
||||
|
||||
## External Dependencies
|
||||
|
||||
|
||||
@@ -9,4 +9,4 @@ The app includes Select2 driven Django Widgets and Form Fields.
|
||||
|
||||
"""
|
||||
|
||||
__version__ = "5.6.0"
|
||||
__version__ = "5.8.8"
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Shared memory across multiple machines to the heavy ajax lookups.
|
||||
Shared memory across multiple machines to the heavy AJAX lookups.
|
||||
|
||||
Select2 uses django.core.cache_ to share fields across
|
||||
multiple threads and even machines.
|
||||
|
||||
Select2 uses the cabhe backend defind in the setting
|
||||
Select2 uses the cache backend defined in the setting
|
||||
``SELECT2_CACHE_BACKEND`` [default=``default``].
|
||||
|
||||
It is advised to always setup a separate cache server for Select2.
|
||||
|
||||
@@ -48,7 +48,7 @@ class Select2Conf(AppConf):
|
||||
It has set `select2_` as a default value, which you can change if needed.
|
||||
"""
|
||||
|
||||
JS = '//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js'
|
||||
JS = '//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'
|
||||
"""
|
||||
The URI for the Select2 JS file. By default this points to the Cloudflare CDN.
|
||||
|
||||
@@ -58,10 +58,10 @@ class Select2Conf(AppConf):
|
||||
SELECT2_JS = 'assets/js/select2.min.js'
|
||||
|
||||
.. tip:: Change this setting to a local asset in your development environment to
|
||||
develop without an internet connection.
|
||||
develop without an Internet connection.
|
||||
"""
|
||||
|
||||
CSS = '//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css'
|
||||
CSS = '//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css'
|
||||
"""
|
||||
The URI for the Select2 CSS file. By default this points to the Cloudflare CDN.
|
||||
|
||||
@@ -71,7 +71,7 @@ class Select2Conf(AppConf):
|
||||
SELECT2_CSS = 'assets/css/select2.css'
|
||||
|
||||
.. tip:: Change this setting to a local asset in your development environment to
|
||||
develop without an internet connection.
|
||||
develop without an Internet connection.
|
||||
"""
|
||||
|
||||
class Meta:
|
||||
|
||||
+90
-65
@@ -50,13 +50,15 @@ from __future__ import absolute_import, unicode_literals
|
||||
|
||||
from functools import reduce
|
||||
from itertools import chain
|
||||
from pickle import PicklingError
|
||||
|
||||
from django import forms
|
||||
from django.core import signing
|
||||
from django.core.urlresolvers import reverse_lazy
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.db.models import Q
|
||||
from django.forms.models import ModelChoiceIterator
|
||||
from django.utils.encoding import force_text
|
||||
from django.utils.six.moves.cPickle import PicklingError as cPicklingError
|
||||
|
||||
from .cache import cache
|
||||
from .conf import settings
|
||||
@@ -87,10 +89,10 @@ class Select2Mixin(object):
|
||||
attrs['class'] = 'django-select2'
|
||||
return attrs
|
||||
|
||||
def render_options(self, choices, selected_choices):
|
||||
def render_options(self, *args, **kwargs):
|
||||
"""Render options including an empty one, if the field is not required."""
|
||||
output = '<option></option>' if not self.is_required else ''
|
||||
output += super(Select2Mixin, self).render_options(choices, selected_choices)
|
||||
output = '<option></option>' if not self.is_required and not self.allow_multiple_selected else ''
|
||||
output += super(Select2Mixin, self).render_options(*args, **kwargs)
|
||||
return output
|
||||
|
||||
def _get_media(self):
|
||||
@@ -115,7 +117,7 @@ class Select2TagMixin(object):
|
||||
"""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', [",", " "])
|
||||
self.attrs.setdefault('data-token-separators', '[",", " "]')
|
||||
return super(Select2TagMixin, self).build_attrs(extra_attrs, **kwargs)
|
||||
|
||||
|
||||
@@ -170,18 +172,17 @@ class Select2TagWidget(Select2TagMixin, Select2Mixin, forms.SelectMultiple):
|
||||
pass
|
||||
|
||||
|
||||
class HeavySelect2Mixin(Select2Mixin):
|
||||
"""Mixin that adds select2's ajax options and registers itself on django's cache."""
|
||||
class HeavySelect2Mixin(object):
|
||||
"""Mixin that adds select2's AJAX options and registers itself on Django's cache."""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
"""
|
||||
Return HeavySelect2Mixin.
|
||||
|
||||
:param data_view: url pattern name
|
||||
:type data_view: str
|
||||
:param data_url: url
|
||||
:type data_url: str
|
||||
:return:
|
||||
Args:
|
||||
data_view (str): URL pattern name
|
||||
data_url (str): URL
|
||||
|
||||
"""
|
||||
self.data_view = kwargs.pop('data_view', None)
|
||||
self.data_url = kwargs.pop('data_url', None)
|
||||
@@ -191,13 +192,13 @@ class HeavySelect2Mixin(Select2Mixin):
|
||||
super(HeavySelect2Mixin, self).__init__(**kwargs)
|
||||
|
||||
def get_url(self):
|
||||
"""Return url from instance or by reversing :attr:`.data_view`."""
|
||||
"""Return URL from instance or by reversing :attr:`.data_view`."""
|
||||
if self.data_url:
|
||||
return self.data_url
|
||||
return reverse_lazy(self.data_view)
|
||||
return reverse(self.data_view)
|
||||
|
||||
def build_attrs(self, extra_attrs=None, **kwargs):
|
||||
"""Set select2's ajax attributes."""
|
||||
"""Set select2's AJAX attributes."""
|
||||
attrs = super(HeavySelect2Mixin, self).build_attrs(extra_attrs=extra_attrs, **kwargs)
|
||||
|
||||
# encrypt instance Id
|
||||
@@ -212,9 +213,9 @@ class HeavySelect2Mixin(Select2Mixin):
|
||||
attrs['class'] += ' django-select2-heavy'
|
||||
return attrs
|
||||
|
||||
def render(self, name, value, attrs=None, choices=()):
|
||||
def render(self, *args, **kwargs):
|
||||
"""Render widget and register it in Django's cache."""
|
||||
output = super(HeavySelect2Mixin, self).render(name, value, attrs=attrs, choices=choices)
|
||||
output = super(HeavySelect2Mixin, self).render(*args, **kwargs)
|
||||
self.set_to_cache()
|
||||
return output
|
||||
|
||||
@@ -222,37 +223,52 @@ class HeavySelect2Mixin(Select2Mixin):
|
||||
return "%s%s" % (settings.SELECT2_CACHE_PREFIX, id(self))
|
||||
|
||||
def set_to_cache(self):
|
||||
"""Add widget object to Djnago's cache."""
|
||||
cache.set(self._get_cache_key(), {
|
||||
'widget': self,
|
||||
'url': self.get_url(),
|
||||
})
|
||||
"""
|
||||
Add widget object to Django's cache.
|
||||
|
||||
def render_options(self, choices, selected_choices):
|
||||
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(),
|
||||
})
|
||||
except (PicklingError, cPicklingError, AttributeError):
|
||||
msg = "You need to overwrite \"set_to_cache\" or ensure that %s is serialisable."
|
||||
raise NotImplementedError(msg % self.__class__.__name__)
|
||||
|
||||
def render_options(self, *args):
|
||||
"""Render only selected options."""
|
||||
choices = chain(choices, self.choices)
|
||||
output = ['<option></option>' if not self.is_required else '']
|
||||
choices = {(k, v) for k, v in choices if k in selected_choices}
|
||||
try:
|
||||
selected_choices, = args
|
||||
except ValueError: # Signature contained `choices` prior to Django 1.10
|
||||
choices, selected_choices = args
|
||||
choices = chain(self.choices, choices)
|
||||
else:
|
||||
choices = self.choices
|
||||
output = ['<option></option>' if not self.is_required and not self.allow_multiple_selected else '']
|
||||
selected_choices = {force_text(v) for v in selected_choices}
|
||||
choices = {(k, v) for k, v in choices if force_text(k) in selected_choices}
|
||||
for option_value, option_label in choices:
|
||||
output.append(self.render_option(selected_choices, option_value, option_label))
|
||||
return '\n'.join(output)
|
||||
|
||||
|
||||
class HeavySelect2Widget(HeavySelect2Mixin, forms.Select):
|
||||
class HeavySelect2Widget(HeavySelect2Mixin, Select2Widget):
|
||||
"""
|
||||
Select2 widget with AJAX support that registers itself to Django's Cache.
|
||||
|
||||
Usage example::
|
||||
|
||||
class MyWidget(HeavySelectWidget):
|
||||
class MyWidget(HeavySelect2Widget):
|
||||
data_view = 'my_view_name'
|
||||
|
||||
or::
|
||||
|
||||
class MyForm(forms.Form):
|
||||
my_field = forms.ChoicesField(
|
||||
widget=HeavySelectWidget(
|
||||
widget=HeavySelect2Widget(
|
||||
data_url='/url/to/json/response'
|
||||
)
|
||||
)
|
||||
@@ -262,13 +278,13 @@ class HeavySelect2Widget(HeavySelect2Mixin, forms.Select):
|
||||
pass
|
||||
|
||||
|
||||
class HeavySelect2MultipleWidget(HeavySelect2Mixin, forms.SelectMultiple):
|
||||
class HeavySelect2MultipleWidget(HeavySelect2Mixin, Select2MultipleWidget):
|
||||
"""Select2 multi select widget similar to :class:`.HeavySelect2Widget`."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class HeavySelect2TagWidget(Select2TagMixin, HeavySelect2MultipleWidget):
|
||||
class HeavySelect2TagWidget(HeavySelect2Mixin, Select2TagWidget):
|
||||
"""Select2 tag widget."""
|
||||
|
||||
pass
|
||||
@@ -284,7 +300,7 @@ class ModelSelect2Mixin(object):
|
||||
queryset = None
|
||||
search_fields = []
|
||||
"""
|
||||
Model lookups that are used to filter the queryset.
|
||||
Model lookups that are used to filter the QuerySet.
|
||||
|
||||
Example::
|
||||
|
||||
@@ -301,14 +317,12 @@ class ModelSelect2Mixin(object):
|
||||
"""
|
||||
Overwrite class parameters if passed as keyword arguments.
|
||||
|
||||
:param model: model to select choices from
|
||||
:type model: django.db.models.Model
|
||||
:param queryset: queryset to select choices from
|
||||
:type queryset: django.db.models.query.QuerySet
|
||||
:param search_fields: list of model lookup strings
|
||||
:type search_fields: list
|
||||
:param max_results: max. JsonResponse view page size
|
||||
:type max_results: int
|
||||
Args:
|
||||
model (django.db.models.Model): Model to select choices from.
|
||||
queryset (django.db.models.QuerySet): QuerySet to select choices from.
|
||||
search_fields (list): List of model lookup strings.
|
||||
max_results (int): Max. JsonResponse view page size.
|
||||
|
||||
"""
|
||||
self.model = kwargs.pop('model', self.model)
|
||||
self.queryset = kwargs.pop('queryset', self.queryset)
|
||||
@@ -320,9 +334,9 @@ class ModelSelect2Mixin(object):
|
||||
|
||||
def set_to_cache(self):
|
||||
"""
|
||||
Add widget's attributes to Djnago's cache.
|
||||
Add widget's attributes to Django's cache.
|
||||
|
||||
Split the queryset, to not pickle the result set.
|
||||
Split the QuerySet, to not pickle the result set.
|
||||
"""
|
||||
queryset = self.get_queryset()
|
||||
cache.set(self._get_cache_key(), {
|
||||
@@ -339,12 +353,14 @@ class ModelSelect2Mixin(object):
|
||||
|
||||
def filter_queryset(self, term, queryset=None):
|
||||
"""
|
||||
Return queryset filtered by search_fields matching the passed term.
|
||||
Return QuerySet filtered by search_fields matching the passed term.
|
||||
|
||||
Args:
|
||||
term (str): Search term
|
||||
|
||||
Returns:
|
||||
QuerySet: Filtered QuerySet
|
||||
|
||||
:param term: Search term
|
||||
:type term: str
|
||||
:return: Filtered queryset
|
||||
:rtype: :class:`.django.db.models.QuerySet`
|
||||
"""
|
||||
if queryset is None:
|
||||
queryset = self.get_queryset()
|
||||
@@ -359,10 +375,11 @@ class ModelSelect2Mixin(object):
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Return queryset based on :attr:`.queryset` or :attr:`.model`.
|
||||
Return QuerySet based on :attr:`.queryset` or :attr:`.model`.
|
||||
|
||||
Returns:
|
||||
QuerySet: QuerySet of available choices.
|
||||
|
||||
:return: queryset of available choices
|
||||
:rtype: :class:`.django.db.models.QuerySet`
|
||||
"""
|
||||
if self.queryset is not None:
|
||||
queryset = self.queryset
|
||||
@@ -384,20 +401,26 @@ class ModelSelect2Mixin(object):
|
||||
return self.search_fields
|
||||
raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__)
|
||||
|
||||
def render_options(self, choices, selected_choices):
|
||||
"""Render only selected options and set queryset from :class:`ModelChoicesIterator`."""
|
||||
output = ['<option></option>' if not self.is_required else '']
|
||||
def render_options(self, *args):
|
||||
"""Render only selected options and set QuerySet from :class:`ModelChoicesIterator`."""
|
||||
try:
|
||||
selected_choices, = args
|
||||
except ValueError:
|
||||
choices, selected_choices = args
|
||||
choices = chain(self.choices, choices)
|
||||
else:
|
||||
choices = self.choices
|
||||
selected_choices = {force_text(v) for v in selected_choices}
|
||||
output = ['<option></option>' if not self.is_required and not self.allow_multiple_selected else '']
|
||||
if isinstance(self.choices, ModelChoiceIterator):
|
||||
if not self.queryset:
|
||||
if self.queryset is None:
|
||||
self.queryset = self.choices.queryset
|
||||
selected_choices = {c for c in selected_choices
|
||||
if c not in self.choices.field.empty_values}
|
||||
choices = {(obj.pk, self.label_from_instance(obj))
|
||||
for obj in self.choices.queryset.filter(pk__in=selected_choices)}
|
||||
else:
|
||||
choices = chain(choices, self.choices)
|
||||
choices = {(k, v) for k, v in choices if k in selected_choices}
|
||||
selected_choices = {force_text(v) for v in selected_choices}
|
||||
choices = {(k, v) for k, v in choices if force_text(k) in selected_choices}
|
||||
for option_value, option_label in choices:
|
||||
output.append(self.render_option(selected_choices, option_value, option_label))
|
||||
return '\n'.join(output)
|
||||
@@ -414,10 +437,12 @@ class ModelSelect2Mixin(object):
|
||||
def label_from_instance(obj):
|
||||
return force_text(obj.title).upper()
|
||||
|
||||
:param obj: Instance of django model.
|
||||
:type obj: django.db.models.Model
|
||||
:return Option label.
|
||||
:rtype: str
|
||||
Args:
|
||||
obj (django.db.models.Model): Instance of Django Model.
|
||||
|
||||
Returns:
|
||||
str: Option label.
|
||||
|
||||
"""
|
||||
return force_text(obj)
|
||||
|
||||
@@ -452,8 +477,8 @@ class ModelSelect2Widget(ModelSelect2Mixin, HeavySelect2Widget):
|
||||
)
|
||||
|
||||
.. tip:: The ModelSelect2(Multiple)Widget will try
|
||||
to get the queryset from the fields choices.
|
||||
Therefore you don't need to define a queryset,
|
||||
to get the QuerySet from the fields choices.
|
||||
Therefore you don't need to define a QuerySet,
|
||||
if you just drop in the widget for a ForeignKey field.
|
||||
"""
|
||||
|
||||
@@ -470,13 +495,13 @@ class ModelSelect2MultipleWidget(ModelSelect2Mixin, HeavySelect2MultipleWidget):
|
||||
pass
|
||||
|
||||
|
||||
class ModelSelect2TagWidget(Select2TagMixin, ModelSelect2MultipleWidget):
|
||||
class ModelSelect2TagWidget(ModelSelect2Mixin, HeavySelect2TagWidget):
|
||||
"""
|
||||
Select2 model widget with tag support.
|
||||
|
||||
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.
|
||||
that adds missing tags to you QuerySet.
|
||||
|
||||
Example::
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Django-Select2 url config.
|
||||
Django-Select2 URL configuration.
|
||||
|
||||
Add `django_select` to your urlconf **if** you use any 'Model' fields::
|
||||
Add `django_select` to your ``urlconf`` **if** you use any 'Model' fields::
|
||||
|
||||
url(r'^select2/', include('django_select2.urls')),
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ class AutoResponseView(BaseListView):
|
||||
})
|
||||
|
||||
def get_queryset(self):
|
||||
"""Get queryset from cached widget."""
|
||||
"""Get QuerySet from cached widget."""
|
||||
return self.widget.filter_queryset(self.term, self.queryset)
|
||||
|
||||
def get_paginate_by(self, queryset):
|
||||
@@ -62,10 +62,12 @@ class AutoResponseView(BaseListView):
|
||||
"""
|
||||
Get and return widget from cache.
|
||||
|
||||
Raises a 404 if the widget can not be found or no id is provided.
|
||||
Raises:
|
||||
Http404: If if the widget can not be found or no id is provided.
|
||||
|
||||
Returns:
|
||||
ModelSelect2Mixin: Widget from cache.
|
||||
|
||||
:raises: Http404
|
||||
:return: ModelSelect2Mixin
|
||||
"""
|
||||
field_id = self.kwargs.get('field_id', self.request.GET.get('field_id', None))
|
||||
if not field_id:
|
||||
|
||||
@@ -46,6 +46,11 @@ html:
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
||||
|
||||
spelling:
|
||||
$(SPHINXBUILD) -b spelling -W $(ALLSPHINXOPTS) $(BUILDDIR)/spelling
|
||||
@echo
|
||||
@echo "Spell check finished. The results are in $(BUILDDIR)/spelling."
|
||||
|
||||
dirhtml:
|
||||
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
|
||||
@echo
|
||||
|
||||
+13
-1
@@ -41,7 +41,14 @@ sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode']
|
||||
extensions = [
|
||||
'sphinx.ext.autodoc',
|
||||
'sphinx.ext.napoleon',
|
||||
'sphinx.ext.inheritance_diagram',
|
||||
'sphinx.ext.intersphinx',
|
||||
'sphinx.ext.viewcode',
|
||||
'sphinxcontrib.spelling',
|
||||
]
|
||||
|
||||
intersphinx_mapping = {
|
||||
'python': ('http://docs.python.org/3.5', None),
|
||||
@@ -49,6 +56,11 @@ intersphinx_mapping = {
|
||||
'https://docs.djangoproject.com/en/dev/_objects/'),
|
||||
}
|
||||
|
||||
# spell check
|
||||
spelling_word_list_filename = 'spelling_wordlist.txt'
|
||||
spelling_show_suggestions = True
|
||||
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ DjangoSelect2 handles the initialization of select2 fields automatically. Just i
|
||||
``{{ form.media.js }}`` in your template before the closing ``body`` tag. That's it!
|
||||
|
||||
If you insert forms after page load or if you want to handle the initialization
|
||||
yourself, DjangoSelect2 provides a jQuery-Plugin. It will handle both normal and
|
||||
yourself, DjangoSelect2 provides a jQuery plugin. It will handle both normal and
|
||||
heavy fields. Simply call ``djangoSelect2(options)`` on your select fields.::
|
||||
|
||||
$('.django-select2').djangoSelect2();
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
Django >= 1.4.1
|
||||
Django >= 1.8
|
||||
sphinxcontrib-spelling
|
||||
pyenchant
|
||||
|
||||
@@ -18,7 +18,8 @@ Installation
|
||||
2. Add ``django_select2`` to your ``INSTALLED_APPS`` in your project settings.
|
||||
|
||||
|
||||
3. Add ``django_select`` to your urlconf **if** you use any 'Auto' fields::
|
||||
3. Add ``django_select`` to your ``urlconf`` **if** you use any
|
||||
:class:`ModelWidgets <.django_select2.forms.ModelSelect2Mixin>`::
|
||||
|
||||
url(r'^select2/', include('django_select2.urls')),
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
jQuery
|
||||
Django
|
||||
mixin
|
||||
backend
|
||||
redis
|
||||
memcached
|
||||
AJAX
|
||||
Cloudflare
|
||||
lookup
|
||||
QuerySet
|
||||
pre
|
||||
py
|
||||
lookups
|
||||
functionalities
|
||||
plugin
|
||||
multi
|
||||
Indices
|
||||
@@ -7,3 +7,6 @@ pep257
|
||||
pytest
|
||||
pytest-django
|
||||
selenium
|
||||
sphinx
|
||||
sphinxcontrib-spelling
|
||||
pyenchant
|
||||
+18
-6
@@ -4,16 +4,28 @@
|
||||
#
|
||||
# pip-compile requirements_dev.in
|
||||
#
|
||||
alabaster==0.7.7 # via sphinx
|
||||
babel==2.2.0 # via sphinx
|
||||
django-appconf==1.0.1
|
||||
flake8==2.5.0
|
||||
docutils==0.12 # via sphinx
|
||||
flake8==2.5.2
|
||||
isort==4.2.2
|
||||
mccabe==0.3.1
|
||||
Jinja2==2.8
|
||||
MarkupSafe==0.23
|
||||
mccabe==0.4.0
|
||||
pep257==0.7.0
|
||||
pep8-naming==0.3.3
|
||||
pep8==1.5.7 # via flake8
|
||||
pep8==1.7.0 # via flake8
|
||||
py==1.4.31 # via pytest
|
||||
pyenchant==1.6.6
|
||||
pyflakes==1.0.0 # via flake8
|
||||
Pygments==2.1
|
||||
pytest-django==2.9.1
|
||||
pytest==2.8.3
|
||||
selenium==2.48.0
|
||||
six==1.10.0 # via django-appconf
|
||||
pytest==2.8.7
|
||||
pytz==2015.7 # via babel
|
||||
selenium==2.50.1
|
||||
six==1.10.0 # via django-appconf, sphinx, sphinxcontrib-spelling
|
||||
snowballstemmer==1.2.1 # via sphinx
|
||||
sphinx-rtd-theme==0.1.9 # via sphinx
|
||||
sphinx==1.3.5
|
||||
sphinxcontrib-spelling==2.1.2
|
||||
|
||||
@@ -17,5 +17,6 @@ atomic = true
|
||||
multi_line_output = 5
|
||||
line_length = 79
|
||||
skip = manage.py,docs
|
||||
known_first_party = django_select2
|
||||
known_first_party = django_select2, tests
|
||||
known_third_party = django
|
||||
combine_as_imports = true
|
||||
|
||||
+62
-8
@@ -9,13 +9,13 @@ from django.core import signing
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.db.models import QuerySet
|
||||
from django.utils.encoding import force_text
|
||||
from django.utils.six import text_type
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from six import text_type
|
||||
|
||||
from django_select2.cache import cache
|
||||
from django_select2.forms import (
|
||||
HeavySelect2Widget, ModelSelect2TagWidget, ModelSelect2Widget,
|
||||
Select2Widget
|
||||
HeavySelect2MultipleWidget, HeavySelect2Widget, ModelSelect2TagWidget,
|
||||
ModelSelect2Widget, Select2Widget
|
||||
)
|
||||
from tests.testapp import forms
|
||||
from tests.testapp.forms import (
|
||||
@@ -27,6 +27,7 @@ from tests.testapp.models import Genre
|
||||
class TestSelect2Mixin(object):
|
||||
url = reverse('select2_widget')
|
||||
form = forms.AlbumSelect2WidgetForm()
|
||||
multiple_form = forms.AlbumSelect2MultipleWidgetForm()
|
||||
widget_cls = Select2Widget
|
||||
|
||||
def test_initial_data(self, genres):
|
||||
@@ -82,6 +83,18 @@ class TestSelect2Mixin(object):
|
||||
widget = HeavySelect2Widget(data_url='/foo/bar')
|
||||
assert widget.get_url() == '/foo/bar'
|
||||
|
||||
def test_empty_option(self, db):
|
||||
# Empty options is only required for single selects
|
||||
# https://select2.github.io/options.html#allowClear
|
||||
single_select = self.form.fields['primary_genre']
|
||||
assert single_select.required is False
|
||||
assert '<option></option>' in single_select.widget.render('primary_genre', None)
|
||||
|
||||
multiple_select = self.multiple_form.fields['featured_artists']
|
||||
assert multiple_select.required is False
|
||||
assert multiple_select.widget.allow_multiple_selected
|
||||
assert '<option></option>' not in multiple_select.widget.render('featured_artists', None)
|
||||
|
||||
|
||||
class TestSelect2MixinSettings(object):
|
||||
def test_default_media(self):
|
||||
@@ -123,14 +136,13 @@ class TestHeavySelect2Mixin(TestSelect2Mixin):
|
||||
not_required_field = self.form.fields['primary_genre']
|
||||
assert not_required_field.required is False
|
||||
assert '<option value="1" selected="selected">One</option>' in \
|
||||
not_required_field.widget.render('primary_genre', 1, choices=NUMBER_CHOICES), \
|
||||
not_required_field.widget.render('primary_genre', 1, choices=NUMBER_CHOICES)
|
||||
not_required_field.widget.render('primary_genre', 1), \
|
||||
not_required_field.widget.render('primary_genre', 1)
|
||||
|
||||
def test_many_selected_option(self, db, genres):
|
||||
field = HeavySelect2MultipleWidgetForm().fields['genres']
|
||||
widget_output = field.widget.render(
|
||||
'genres', [1, 2],
|
||||
choices=NUMBER_CHOICES)
|
||||
field.widget.choices = NUMBER_CHOICES
|
||||
widget_output = field.widget.render('genres', [1, 2])
|
||||
selected_option = '<option value="{pk}" selected="selected">{value}</option>'.format(pk=1, value='One')
|
||||
selected_option2 = '<option value="{pk}" selected="selected">{value}</option>'.format(pk=2, value='Two')
|
||||
|
||||
@@ -154,9 +166,24 @@ class TestHeavySelect2Mixin(TestSelect2Mixin):
|
||||
error = driver.find_element_by_xpath('//body[@JSError]')
|
||||
pytest.fail(error.get_attribute('JSError'))
|
||||
|
||||
def test_get_url(self):
|
||||
widget = self.widget_cls(data_view='heavy_data_1', attrs={'class': 'my-class'})
|
||||
assert isinstance(widget.get_url(), text_type)
|
||||
|
||||
def test_can_not_pickle(self):
|
||||
widget = self.widget_cls(data_view='heavy_data_1', attrs={'class': 'my-class'})
|
||||
|
||||
class NoPickle(object):
|
||||
pass
|
||||
|
||||
widget.no_pickle = NoPickle()
|
||||
with pytest.raises(NotImplementedError):
|
||||
widget.set_to_cache()
|
||||
|
||||
|
||||
class TestModelSelect2Mixin(TestHeavySelect2Mixin):
|
||||
form = forms.AlbumModelSelect2WidgetForm(initial={'primary_genre': 1})
|
||||
multiple_form = forms.ArtistModelSelect2MultipleWidgetForm()
|
||||
|
||||
def test_initial_data(self, genres):
|
||||
genre = genres[0]
|
||||
@@ -269,6 +296,10 @@ class TestModelSelect2Mixin(TestHeavySelect2Mixin):
|
||||
assert isinstance(cached_widget['queryset'][0], qs.__class__)
|
||||
assert text_type(cached_widget['queryset'][1]) == text_type(qs.query)
|
||||
|
||||
def test_get_url(self):
|
||||
widget = ModelSelect2Widget(queryset=Genre.objects.all(), search_fields=['title__icontains'])
|
||||
assert isinstance(widget.get_url(), text_type)
|
||||
|
||||
|
||||
class TestHeavySelect2TagWidget(TestHeavySelect2Mixin):
|
||||
|
||||
@@ -284,3 +315,26 @@ class TestHeavySelect2TagWidget(TestHeavySelect2Mixin):
|
||||
queryset=Genre.objects.all(), search_fields=['title__icontains'], attrs={'data-minimum-input-length': '3'})
|
||||
output = widget.render('name', 'value')
|
||||
assert 'data-minimum-input-length="3"' in output
|
||||
|
||||
|
||||
class TestHeavySelect2MultipleWidget(object):
|
||||
url = reverse('heavy_select2_multiple_widget')
|
||||
form = forms.HeavySelect2MultipleWidgetForm()
|
||||
widget_cls = HeavySelect2MultipleWidget
|
||||
|
||||
def test_widgets_selected_after_validation_error(self, db, live_server, driver):
|
||||
driver.get(live_server + self.url)
|
||||
title = driver.find_element_by_id('id_title')
|
||||
title.send_keys('fo')
|
||||
genres, fartists = driver.find_elements_by_css_selector('.select2-selection--multiple')
|
||||
genres.click()
|
||||
genres.send_keys('o') # results are Zero One Two Four
|
||||
# select second element - One
|
||||
driver.find_element_by_css_selector('.select2-results li:nth-child(2)').click()
|
||||
genres.submit()
|
||||
# there is a ValidationError raised, check for it
|
||||
errstring = driver.find_element_by_css_selector('ul.errorlist li').text
|
||||
assert errstring == "Title must have more than 3 characters."
|
||||
# genres should still have One as selected option
|
||||
result_title = driver.find_element_by_css_selector('.select2-selection--multiple li').get_attribute('title')
|
||||
assert result_title == 'One'
|
||||
|
||||
@@ -13,7 +13,6 @@ from tests.testapp.forms import (
|
||||
AlbumModelSelect2WidgetForm, ArtistCustomTitleWidget
|
||||
)
|
||||
from tests.testapp.models import Genre
|
||||
from django_select2.conf import settings
|
||||
|
||||
|
||||
class TestAutoResponseView(object):
|
||||
|
||||
+15
-2
@@ -117,7 +117,12 @@ class ArtistModelSelect2MultipleWidgetForm(forms.Form):
|
||||
genres = forms.ModelMultipleChoiceField(widget=ModelSelect2MultipleWidget(
|
||||
queryset=models.Genre.objects.all(),
|
||||
search_fields=['title__icontains'],
|
||||
), queryset=models.Genre.objects.all(), required=False)
|
||||
), queryset=models.Genre.objects.all(), required=True)
|
||||
|
||||
featured_artists = forms.ModelMultipleChoiceField(widget=ModelSelect2MultipleWidget(
|
||||
queryset=models.Artist.objects.all(),
|
||||
search_fields=['title__icontains'],
|
||||
), queryset=models.Artist.objects.all(), required=False)
|
||||
|
||||
NUMBER_CHOICES = [
|
||||
(1, 'One'),
|
||||
@@ -144,14 +149,22 @@ class HeavySelect2WidgetForm(forms.Form):
|
||||
|
||||
|
||||
class HeavySelect2MultipleWidgetForm(forms.Form):
|
||||
title = forms.CharField(max_length=50)
|
||||
genres = forms.MultipleChoiceField(
|
||||
widget=HeavySelect2MultipleWidget(data_view='heavy_data_1', choices=NUMBER_CHOICES)
|
||||
widget=HeavySelect2MultipleWidget(data_view='heavy_data_1', choices=NUMBER_CHOICES),
|
||||
choices=NUMBER_CHOICES
|
||||
)
|
||||
featured_artists = forms.MultipleChoiceField(
|
||||
widget=HeavySelect2MultipleWidget(data_view='heavy_data_2', choices=NUMBER_CHOICES),
|
||||
choices=NUMBER_CHOICES,
|
||||
required=False
|
||||
)
|
||||
|
||||
def clean_title(self):
|
||||
if len(self.cleaned_data['title']) < 3:
|
||||
raise forms.ValidationError("Title must have more than 3 characters.")
|
||||
return self.cleaned_data["title"]
|
||||
|
||||
|
||||
class ModelSelect2TagWidgetForm(forms.ModelForm):
|
||||
class Meta:
|
||||
|
||||
@@ -33,9 +33,12 @@ MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
|
||||
SITE_ID = 1
|
||||
ROOT_URLCONF = 'tests.testapp.urls'
|
||||
|
||||
TEMPLATE_DIRS = (
|
||||
os.path.join(BASE_DIR, "templates"),
|
||||
)
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'APP_DIRS': True,
|
||||
},
|
||||
]
|
||||
|
||||
SECRET_KEY = '123456'
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ urlpatterns = [
|
||||
url(r'^heavy_select2_widget/$',
|
||||
TemplateFormView.as_view(form_class=HeavySelect2WidgetForm), name='heavy_select2_widget'),
|
||||
url(r'^heavy_select2_multiple_widget/$',
|
||||
TemplateFormView.as_view(form_class=HeavySelect2MultipleWidgetForm),
|
||||
TemplateFormView.as_view(form_class=HeavySelect2MultipleWidgetForm, success_url='/'),
|
||||
name='heavy_select2_multiple_widget'),
|
||||
|
||||
url(r'^model_select2_widget/$',
|
||||
|
||||
@@ -12,12 +12,16 @@ class TemplateFormView(FormView):
|
||||
|
||||
|
||||
def heavy_data_1(request):
|
||||
term = request.GET.get("term", "")
|
||||
numbers = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five']
|
||||
numbers = filter(lambda num: term.lower() in num.lower(), numbers)
|
||||
results = [{'id': index, 'text': value} for (index, value) in enumerate(numbers)]
|
||||
return HttpResponse(json.dumps({'err': 'nil', 'results': results}), content_type='application/json')
|
||||
|
||||
|
||||
def heavy_data_2(request):
|
||||
term = request.GET.get("term", "")
|
||||
numbers = ['Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Fortytwo']
|
||||
numbers = filter(lambda num: term.lower() in num.lower(), numbers)
|
||||
results = [{'id': index, 'text': value} for (index, value) in enumerate(numbers)]
|
||||
return HttpResponse(json.dumps({'err': 'nil', 'results': results}), content_type='application/json')
|
||||
|
||||
Reference in New Issue
Block a user