Compare commits

...

201 commits

Author SHA1 Message Date
Benbb96
e7fa49a6e2
Prevent literal "None" placeholders (#591) 2020-02-25 11:50:21 +01:00
Johannes Hoppe
39ab326884 Add support for Django 3.0 2020-01-05 17:23:31 +01:00
Mario Frasca
d63f410bca Improve getting started documentation (#542) 2019-12-13 14:52:03 +01:00
Adrien Delhorme
5680f0daf9 Update Select2 library to version 4.0.12 2019-11-21 22:27:02 +07:00
Johannes Hoppe
8deb2b6a11
Create FUNDING.yml 2019-10-30 10:09:30 +09:00
Johannes Hoppe
37e2515be6
Add name to setup.py to enable GH dependency graph 2019-10-29 11:30:12 +09:00
Johannes Hoppe
cc8989a625 Fix typo 2019-10-10 13:09:03 -10:00
Johannes Hoppe
1ae52d7436 Fix #574 -- Update jQuery documentation
Update jQuery documentation to reflect jQuery versino support.
2019-10-10 13:09:03 -10:00
Johannes Hoppe
dca7dbc5d1 Fix #565 -- Support empty_label on ModelSelect fields. 2019-08-26 17:13:27 +02:00
predatell
8bd7f7209f Try to get queryset form choices, if possible (#509)
Get queryset for model widgets from choices. This omits the need to explicitly supply a queryset or model to the widget.
2019-07-09 18:38:59 +02:00
Johannes Hoppe
6b1ca10b06 Fix typo 2019-07-08 18:57:23 +02:00
Johannes Hoppe
4f96e21333 Resolve #557 -- Improve documentation for ModelSelect2TagWidget 2019-07-08 18:57:23 +02:00
Johannes Hoppe
8494b10fcc Fix pycodestyle issue 2019-06-10 18:03:23 +02:00
Johannes Hoppe
ff68bf1050 Fix #550 -- Omit tests from wheel 2019-06-10 18:03:23 +02:00
Mario Frasca
c15de464d5 Fix #544 -- Ensure correct attribute defaults (#547)
dict.setdefault() does not change the default value if called twice.
Therefore, defaults need to passed to the super call instead.
2019-06-10 17:09:04 +02:00
Vipul Chaudhary
898b2e84dd Fix #418 –– Remove extra Q created in the ORM query (#548)
The iterator for reduce function should not have the first element
select &= reduce(lambda x, y: x | Q(**{y: t}), search_fields[1:], Q(**{search_fields[0]: t}))
2019-06-10 16:57:17 +02:00
Pablo Montepagano
1e4056bd62 fixed typo in docs 2019-06-10 16:54:36 +02:00
Johannes Hoppe
2bb6f3a974 Set Sphinx project settings in conf.py file 2019-04-11 12:29:40 +02:00
Johannes Hoppe
fa9d8baba8 Set master_doc for readthedocs 2019-04-11 12:21:12 +02:00
Johannes Hoppe
df5bf9e893 Fix travis deployment pipeline 2019-04-10 14:05:57 +02:00
Johannes Hoppe
4d0d702aaf Don't skip after_success 2019-04-10 13:50:22 +02:00
Johannes Hoppe
0c82edf65c Fix release process 2019-04-10 13:34:15 +02:00
Johannes Hoppe
0021f35b2a Use setuptools_scm for versioning 2019-04-10 11:58:40 +02:00
Johannes Hoppe
ad42a01083 Fix #535 -- Add static files to dist package 2019-04-10 11:58:40 +02:00
Johannes Hoppe
3a7ecd1666 Move deploy to base level 2019-04-08 20:20:51 +02:00
Johannes Hoppe
2f17e21b0b Simplify package setup 2019-04-08 19:57:22 +02:00
Johannes Hoppe
9de7f29815
Update issue templates 2019-04-05 15:33:02 +02:00
Johannes Hoppe
ffe91627d8 Add documentation for new request argument 2019-03-23 13:57:13 +01:00
Johannes Hoppe
66d2051c20 Fix django master 2019-03-23 13:57:13 +01:00
Johannes Hoppe
48ceeaa312 Update travis-contif 2019-03-23 13:57:13 +01:00
Johannes Hoppe
9b54cc30c7 Add Django 2.2 support
Add Django 2.2 LTS support
Drop Django 1.11 LTS support
Add request argument to `ModelSelect2Mixin.filter_queryset`
2019-03-23 13:57:13 +01:00
Andrew Benedict Wallace
82859121a6 Update get_started.rst (#513)
explicit import to help us find Select2MultipleWidget
2018-09-06 08:13:59 +02:00
Johannes Hoppe
d34cd2e5de
Enable check suite (#508) 2018-08-27 14:14:19 +02:00
Thomas Grainger
e4efaab6f1 Fix automated NPM deployment process (#505)
Use skip_cleanup to distribute build artifacts.
2018-08-23 18:59:21 +02:00
Johannes Hoppe
1e8971c12b
Fix travis config (#504) 2018-08-22 13:49:55 +02:00
Thomas Grainger
de7e7a1903 Publish django-select2 JavaScript code on NPM (#479) 2018-08-22 12:04:02 +02:00
Johannes Hoppe
0f18958099
Add Python 3.7 support (#502) 2018-08-18 14:36:06 +02:00
Johannes Hoppe
ebbdd2b9be
Add support for Django 2.1 (#501) 2018-08-18 13:56:39 +02:00
Johannes Hoppe
e9d96cf856
Cleanup docs build (#466) 2018-08-18 13:52:54 +02:00
Johannes Hoppe
f6eaa26c16 Fix #493 -- Fix Python 3.5 compatibility
Ref 1954bf57fa
2018-08-05 11:53:10 +02:00
Johannes Hoppe
73d4be8992 Switch Chrome Driver to package 2018-07-27 16:22:17 +02:00
Johannes Hoppe
e1d42bfcad Update Select2 library to version 4.0.5 2018-07-24 13:05:11 +02:00
Johannes Hoppe
1954bf57fa Add SELECT2_LIB_VERSION setting
The new setting allows to change to default library version to
a specific value without overriding all URLs individually.
2018-07-24 13:05:11 +02:00
Asger Hautop Drewsen
08ca1c1c36 Add note about Select2 support in Django 2.0 admin (#488)
Resolve #485
2018-07-01 10:37:30 +02:00
Bill Yeh
aef27f48df Add option to exclude the Select2 library from form media (#484) 2018-06-30 14:58:47 +02:00
Johannes Hoppe
f31beec0c4
Add support for custom to_field names for foreign keys (#486)
Django's ForeignKey supports custom to_fields. The to field is the
primary key by default, but can be modified. The to field is also
used by forms to reduce database lookups.

This patch add support for custom to_field names on both model or
form layer.
2018-06-30 14:56:32 +02:00
dzhuang
496cc7c502 Fallback i18n js files for zh-hans/zh-hant. (#468)
* Fallback i18n js files for zh-hans/zh-hant.

* Use Django admin's built-in SELECT2_TRANSLATIONS to determine the lang of i18n js files.
2018-06-14 11:49:47 +02:00
Jan Pieter Waagmeester
17af750d88 Link to stable Django version docs not 1.8 (#480) 2018-05-31 09:30:22 +02:00
Jan Pieter Waagmeester
67bf060991 Link to github releases from readme+changelog. (#481) 2018-05-31 09:29:18 +02:00
Johannes Hoppe
d9c899e8f7 Resolve pickle security note 2018-05-07 18:52:17 +02:00
Johannes Hoppe
e4729feb9a Add bandit config 2018-05-07 18:52:17 +02:00
Jan Pieter Waagmeester
2ea6ef8edb Fix typo in docstring ChoicesField -> ChoiceField (#472)
It's `django.forms.ChoiceField`, not `django.forms.ChoicesField`.

Used correctly here: 
a9aa31146f/django_select2/forms.py (L143)
2018-05-06 13:02:38 +02:00
Sergey Fedoseev
a9aa31146f Fixed display of ModelSelect2Mixin.filter_queryset() doc. (#470) 2018-03-24 14:25:42 +01:00
Inti Ocean
c2331b272a Add some quickstart docs (#467)
Add some quickstart docs to make it easy for someone to pick up the library and get going
straight away.
2018-03-19 12:09:54 +01:00
Johannes Hoppe
5d98048c9f
Fix #464 -- Freeze Sphinx to 1.6.5
Ref sphinx/shpinx#4520
2018-03-07 22:36:43 +01:00
Johannes Hoppe
7782e9bc3d
Fix #461 -- Remove explicit Django version classifiers 2018-02-17 15:05:46 +01:00
Alessio Ferri
426cace3a3 Improving documentation (#455) 2018-02-02 10:26:51 +01:00
Johannes Hoppe
90fbf7422f
Fix #451 -- Remove none ASCII char 2018-01-10 18:19:13 +01:00
Johannes Hoppe
f6d5afe51d Add support for Django 2.0 2017-11-25 18:56:46 +01:00
Johannes Hoppe
19e2e50921 Drop Django 1.8 and 1.10 support 2017-11-25 18:56:46 +01:00
Johannes Hoppe
937dcac08b Drop Python 3.5 support 2017-11-25 18:56:46 +01:00
Johannes Hoppe
322b389ad3 Increment version number 2017-11-25 18:56:46 +01:00
Johannes Hoppe
ac7050d2db Fix coerage badge 2017-11-25 18:56:46 +01:00
Johannes Hoppe
d4dcc5f3c0 Switch to short version of APL2 2017-11-25 18:56:46 +01:00
Johannes Hoppe
cca6583d48 Switch README to reStructuredText 2017-11-25 18:56:46 +01:00
Johannes Hoppe
1b1f345b3d Switch releases to pbr 2017-11-25 18:56:46 +01:00
Johannes Hoppe
e09951ce62 Unfreeze development requirements 2017-11-25 18:56:46 +01:00
Johannes Hoppe
f967eb643b Drop Python 2 support 2017-11-25 18:56:46 +01:00
Jens Timmerman
176be2fdcf Update setup.cfg (#446)
not all build systems running `python setup.py bdist_rpm`  will generate a setup.cfg if one is already present
so we need to repeat the dependencies from setup.py in setup.cfg's bdist_rpm section if we want to create correct dependencies  in the rpm's generated. (django appconf 0.6 is called python-django-appconf in redhat/centos/fedora)
2017-11-23 12:51:54 +01:00
Johannes Hoppe
e1f5b7d999 Switch from coveralls to codecov 2017-11-10 09:47:12 +01:00
pyup-bot
5f263f9385 Update jinja2 from 2.9.6 to 2.10 2017-11-09 13:46:01 +01:00
pyup-bot
3ebad0dc12 Update coverage from 4.4.1 to 4.4.2 2017-11-05 16:01:56 +01:00
pyup-bot
00c082bd6d Update selenium from 3.6.0 to 3.7.0 2017-11-03 10:20:18 +01:00
pyup-bot
3cc666e46d Update pytz from 2017.2 to 2017.3 2017-11-01 13:53:56 +01:00
pyup-bot
47c191fe13 Update flake8 from 3.4.1 to 3.5.0 2017-10-24 20:37:37 +02:00
pyup-bot
4ebbb05d11 Update pep8 from 1.7.0 to 1.7.1 2017-10-24 20:35:32 +02:00
pyup-bot
4ba7ecb8a0 Update sphinx from 1.6.4 to 1.6.5 2017-10-23 09:43:50 +02:00
pyup-bot
2b2b11fdf4 Update sphinxcontrib-spelling from 4.0.0 to 4.0.1 2017-10-11 22:39:02 +02:00
pyup-bot
88319ecc47 Update sphinxcontrib-spelling from 2.3.0 to 4.0.0 2017-10-11 10:22:16 +02:00
pyup-bot
4c0139f253 Update pydocstyle from 2.1.0 to 2.1.1 2017-10-10 11:58:18 +02:00
pyup-bot
fdfdbbb512 Update pydocstyle from 2.0.0 to 2.1.0 2017-10-08 20:02:44 +02:00
pyup-bot
15201d1c7e Update pytest from 3.2.2 to 3.2.3 2017-10-05 10:20:22 +02:00
pyup-bot
da6867c083 Update sphinx from 1.6.3 to 1.6.4 2017-09-28 16:55:38 +02:00
pyup-bot
6153f4778a Update selenium from 3.5.0 to 3.6.0 2017-09-28 16:55:25 +02:00
pyup-bot
58d8a9faa8 Update six from 1.10.0 to 1.11.0 2017-09-18 15:41:21 +02:00
pyup-bot
1a27c3562d Update babel from 2.5.0 to 2.5.1 2017-09-14 13:09:38 +02:00
pyup-bot
b81b7f4d0c Update pytest from 3.2.1 to 3.2.2 2017-09-07 21:01:07 +02:00
Aaron WALKER
c07194e382 Fix incorrect i18n documentation 2017-09-07 16:40:31 +02:00
Phoebe Bright
c4b3fdfbef Add model to AddressForm example
model also seems to be required in widget as shown in test - https://github.com/applegrew/django-select2/blob/master/tests/testapp/forms.py
2017-08-31 00:27:21 +02:00
pyup-bot
2000395c3b Update babel from 2.4.0 to 2.5.0 2017-08-18 11:41:13 +02:00
pyup-bot
8911ad91b2 Update redis from 2.10.5 to 2.10.6 2017-08-17 09:18:33 +02:00
pyup-bot
5dec946658 Update selenium from 3.4.3 to 3.5.0 2017-08-10 17:55:26 +02:00
pyup-bot
85ffeda276 Update pytest from 3.2.0 to 3.2.1 2017-08-10 09:23:16 +02:00
pyup-bot
44d0039d49 Update pyflakes from 1.5.0 to 1.6.0 2017-08-03 18:06:43 +02:00
pyup-bot
a3f4a28ff1 Update docutils from 0.13.1 to 0.14 2017-08-03 16:09:39 +02:00
pyup-bot
403a32ff46 Update pytest from 3.1.3 to 3.2.0 2017-08-02 10:12:02 +02:00
pyup-bot
cca167bd24 Update flake8 from 3.3.0 to 3.4.1 2017-07-31 13:27:36 +02:00
Johannes Hoppe
90028d9e36 Fix case issue -- get_langauge() only returns lower case
get_langauge() only returns lower case some i18n file name include
upper case language code tho. This will detect all lanugages.
2017-07-24 10:25:56 +02:00
pyup-bot
ec3462e87a Update pyenchant from 1.6.10 to 1.6.11 2017-07-21 14:29:05 +02:00
pyup-bot
db5ec06f83 Update pyenchant from 1.6.8 to 1.6.10 2017-07-19 13:54:39 +02:00
Johannes Hoppe
b46f69f166 Add i18n support 2017-07-16 17:30:42 +02:00
Johannes Hoppe
b88e26bfa2 Switch to Chrome headless for selenium tests 2017-07-16 12:35:11 +02:00
pyup-bot
78c54f2c47 Update pytest from 3.1.2 to 3.1.3 2017-07-08 14:54:21 +02:00
Yuval Adam
018701680b Update ArrayField tagging widget documentation
This change reflects the new widget rendering APIs in Django 1.11
and enables the tagging widget to correctly show existing tags
2017-07-03 15:21:52 +02:00
pyup-bot
d4668e3125 Update selenium from 3.4.2 to 3.4.3 2017-07-03 11:04:48 +02:00
pyup-bot
bc0eab96e0 Update sphinx from 1.6.2 to 1.6.3 2017-07-03 11:04:33 +02:00
pyup-bot
6d2bd1cbd3 Update pytest-rerunfailures from 2.1.0 to 2.2 2017-07-03 11:04:21 +02:00
pyup-bot
9d215f6efe Update pytest from 3.1.1 to 3.1.2 2017-06-11 10:38:32 +02:00
pyup-bot
5741279d0e Update py from 1.4.33 to 1.4.34 2017-06-09 11:46:26 +02:00
pyup-bot
12b0d472b8 Update isort from 4.2.13 to 4.2.15 2017-06-09 11:25:51 +02:00
pyup-bot
74d2266817 Update isort from 4.2.9 to 4.2.13 2017-06-04 12:31:29 +02:00
pyup-bot
c46fd5a5ec Update isort from 4.2.5 to 4.2.9 2017-06-01 17:38:59 +02:00
pyup-bot
ad938c6008 Update pytest from 3.1.0 to 3.1.1 2017-06-01 17:37:52 +02:00
pyup-bot
2c1ae2df92 Update sphinx from 1.6.1 to 1.6.2 2017-05-29 14:57:15 +02:00
Johannes Hoppe
6260226ae5 Remove PhantomJS test runs 2017-05-25 12:09:07 +02:00
pyup-bot
a5bb222ea8 Update pytest from 3.0.7 to 3.1.0 2017-05-23 09:14:38 +02:00
pyup-bot
f12e624cb8 Update selenium from 3.4.1 to 3.4.2 2017-05-19 10:04:30 +02:00
pyup-bot
c0d6fcb663 Update sphinx from 1.5.6 to 1.6.1 2017-05-17 11:54:37 +02:00
pyup-bot
6dc2f3eb19 Update coverage from 4.4 to 4.4.1 2017-05-17 11:54:31 +02:00
Johannes Hoppe
26f2a36dc6 Update tests suite for wait for browser to be loaded 2017-05-17 11:54:16 +02:00
pyup-bot
d6180e05fc Update selenium from 3.3.3 to 3.4.1 2017-05-17 11:54:16 +02:00
Johannes Hoppe
67b7e755fe Add reruns for flaky selenium tests 2017-05-17 11:53:25 +02:00
Johannes Hoppe
4147cac2f8 Add 100ms implicit wait time to selenium driver 2017-05-17 11:53:25 +02:00
Johannes Hoppe
55e481470e Update selenium drivers 2017-05-17 11:53:25 +02:00
pyup-bot
7297ed7fde Update sphinx from 1.5.5 to 1.5.6 2017-05-15 10:48:29 +02:00
pyup-bot
90be63441b Update coverage from 4.3.4 to 4.4 2017-05-08 19:32:09 +02:00
pyup-bot
d6e056c009 Update django-redis from 4.7.0 to 4.8.0 2017-04-25 17:23:30 +02:00
pyup-bot
a910581f7a Update pydocstyle from 1.1.1 to 2.0.0 2017-04-19 11:30:11 +02:00
Alexey Ruzin
1931a98240 Chained select2 2017-04-18 10:57:33 +02:00
Johannes Hoppe
5840622794 Add support for Django 1.11
Drop support for Django 1.9
2017-04-14 14:09:23 +02:00
pyup-bot
dc6e87e7ba Update selenium from 3.3.1 to 3.3.3 2017-04-07 15:02:11 +02:00
pyup-bot
71a836c892 Update sphinx from 1.5.4 to 1.5.5 2017-04-04 11:18:10 +02:00
pyup-bot
735d5931d6 Update jinja2 from 2.9.5 to 2.9.6 2017-04-03 15:48:09 +02:00
pyup-bot
9cc0a9d62d Update sphinx from 1.5.3 to 1.5.4 2017-04-03 14:30:26 +02:00
pyup-bot
dfdc626ad3 Update pytz from 2016.10 to 2017.2 2017-03-30 15:18:43 +02:00
pyup-bot
07e8029026 Update babel from 2.3.4 to 2.4.0 2017-03-27 09:41:41 +02:00
pyup-bot
1f9d564445 Update py from 1.4.32 to 1.4.33 2017-03-17 18:30:29 +01:00
pyup-bot
5099b8d44d Update pytest from 3.0.6 to 3.0.7 2017-03-15 10:52:18 +01:00
pyup-bot
8958940c43 Update selenium from 3.3.0 to 3.3.1 2017-03-13 20:55:49 +01:00
pyup-bot
d6202c4108 Update selenium from 3.0.2 to 3.3.0 2017-03-08 14:00:49 +01:00
pyup-bot
0d560c08fc Update markupsafe from 0.23 to 1.0 2017-03-07 17:20:29 +01:00
pyup-bot
17dff07690 Update sphinx-rtd-theme from 0.2.2 to 0.2.4 2017-03-07 10:47:01 +01:00
pyup-bot
c6d7054e16 Update sphinx-rtd-theme from 0.2.0 to 0.2.2 2017-03-04 12:54:11 +01:00
pyup-bot
a89fedbe75 Update alabaster from 0.7.9 to 0.7.10 2017-03-02 14:30:11 +01:00
pyup-bot
0918cae3e7 Update sphinx-rtd-theme from 0.1.9 to 0.2.0 2017-03-02 14:29:52 +01:00
pyup-bot
8f6e33845e Update sphinx from 1.5.2 to 1.5.3 2017-02-27 16:03:07 +01:00
pyup.io bot
46a50f377b Update pygments from 2.1.3 to 2.2.0 (#316) 2017-02-23 10:05:12 +01:00
Johannes Hoppe
895a7e519a Reformat JS to match StandardJS style 2017-02-23 10:04:36 +01:00
Johannes Hoppe
c235c2e3f0 Add standardjs linter 2017-02-23 10:04:36 +01:00
pyup-bot
9a658b3b0f Update sphinx from 1.5.1 to 1.5.2 2017-02-22 13:24:31 +01:00
pyup-bot
efb120b47d Update pytest from 3.0.5 to 3.0.6 2017-02-22 13:24:04 +01:00
pyup-bot
b34642dcef Update pyflakes from 1.4.0 to 1.5.0 2017-02-22 13:22:27 +01:00
pyup-bot
8b64b5d4fa Update mccabe from 0.5.3 to 0.6.1 2017-02-22 13:22:10 +01:00
pyup-bot
4e8b2c24a3 Update jinja2 from 2.8.1 to 2.9.5 2017-02-22 13:21:41 +01:00
Johannes Hoppe
23e91c8bb0 Fix flaky test 2017-02-22 13:21:30 +01:00
pyup-bot
e88c0e059c Update flake8 from 3.2.1 to 3.3.0 2017-02-21 15:53:52 +01:00
pyup-bot
047ee28722 Update coverage from 4.3.1 to 4.3.4 2017-02-21 15:37:05 +01:00
Johannes Hoppe
6018b60fea Wait for form to be submitted 2017-02-21 15:07:19 +01:00
Johannes Hoppe
f1e0752f2d Update gecko driver to 0.14.0 2017-02-21 15:07:19 +01:00
Johannes Hoppe
172ef79ffd Fix coverage source configuration 2017-02-21 15:07:19 +01:00
Johannes Hoppe
36a9ab7bab Fix pytest config 2017-02-21 15:07:19 +01:00
Johannes Hoppe
09110a5460 Fix syntax 2017-02-21 15:07:19 +01:00
pyup-bot
ec1c81ad87 Update mccabe from 0.4.0 to 0.5.3 2017-02-21 15:07:19 +01:00
pyup-bot
3673e55195 Update pyflakes from 1.0.0 to 1.4.0 2017-02-21 15:07:19 +01:00
pyup-bot
937874127f Update pep8-naming from 0.3.3 to 0.4.1 2017-02-21 15:07:19 +01:00
pyup-bot
681ced9f15 Update coverage from 4.3 to 4.3.1 2017-02-21 15:07:19 +01:00
pyup-bot
e375a58b4d Update flake8 from 2.5.2 to 3.2.1 2017-02-21 15:07:19 +01:00
pyup-bot
b2609256f5 Update django-redis from 4.6.0 to 4.7.0 2017-02-21 15:07:19 +01:00
pyup-bot
b676e563e2 Update docutils from 0.12 to 0.13.1 2017-02-21 15:07:19 +01:00
pyup-bot
65cfc12be3 Update pyenchant from 1.6.6 to 1.6.8 2017-02-21 15:07:19 +01:00
pyup-bot
e6ace9a8bc Update babel from 2.2.0 to 2.3.4 2017-02-21 15:07:19 +01:00
pyup-bot
c3a48de1a3 Update django-appconf from 1.0.1 to 1.0.2 2017-02-21 15:07:19 +01:00
pyup-bot
8a463752a0 Update pygments from 2.1 to 2.1.3 2017-02-21 15:07:19 +01:00
pyup-bot
c364394450 Update isort from 4.2.2 to 4.2.5 2017-02-21 15:07:19 +01:00
pyup-bot
977f2c3e25 Update py from 1.4.31 to 1.4.32 2017-02-21 15:07:19 +01:00
pyup-bot
aa15810d92 Update pytz from 2015.7 to 2016.10 2017-02-21 15:07:19 +01:00
pyup-bot
4a5c13a35f Update pytest-django from 2.9.1 to 3.1.2 2017-02-21 15:07:19 +01:00
pyup-bot
584e2e9f89 Update alabaster from 0.7.7 to 0.7.9 2017-02-21 15:07:19 +01:00
pyup-bot
33a7e03acf Update jinja2 from 2.8 to 2.8.1 2017-02-21 15:07:19 +01:00
pyup-bot
93dab02fd1 Update sphinx from 1.3.5 to 1.5.1 2017-02-21 15:07:19 +01:00
pyup-bot
d364dc9630 Update sphinxcontrib-spelling from 2.1.2 to 2.3.0 2017-02-21 15:07:19 +01:00
pyup-bot
701d57ef31 Update selenium from 2.50.1 to 3.0.2 2017-02-21 15:07:19 +01:00
pyup-bot
71c6e1d9c3 Update pytest from 2.8.7 to 3.0.5 2017-02-21 15:07:19 +01:00
Tim Tisdall
7c2a898cfa update CHANGELOG 2017-01-23 20:01:03 +01:00
Johannes Hoppe
6180846345 Update test suite
- Add tox
- Add python 3.6
- Drop python 3.4
- Add chrome and gecko driver
- Switch tests from memcache to redis
2016-12-28 21:02:32 +01:00
Tim Tisdall
9430a950c2 refer to the correct class 2016-12-05 14:54:11 +01:00
Johannes Hoppe
1f9b094b67 v5.8.10 2016-12-05 14:52:54 +01:00
Tim Tisdall
15dbbf41a7 retain order of choices
If the choices are put into a `set` then the order is lost.  Regardless, I don't think a `set` is very useful here as this won't even deal with duplicate choice values/ids (ex. `(('1', 'one'), ('1', 'also one'))`)
2016-12-05 14:47:49 +01:00
Raony Guimarães
fb3bc19595 Fix Test suite for Django 1.10+
* Fix template dir

This is necessary to make your example work!

* Fix Jquery2 url
2016-11-04 15:52:29 +01:00
Johannes Hoppe
f03d7d44a8 Add tests for Django 1.10 release 2016-08-25 10:05:22 +02:00
Johannes Hoppe
e3c6919bbd Fix tests 2016-08-15 09:07:57 +02:00
Johannes Hoppe
9f5644b479 Upgrade select2 to 4.0.3 2016-08-15 08:58:34 +02:00
Johannes Hoppe
c797e59584 Bump version number to 5.8.7 2016-08-14 10:41:31 +02:00
Josef Kolář
72616f8276 ModelSelect2Mixin - avoid queryset evaluation (#287) 2016-08-14 10:38:57 +02:00
Johannes Hoppe
99aed19308 Write changelog bump version to 5.8.6 2016-06-19 12:29:45 +02:00
Jonas Haag
74bf15ce48 Drop six requirement, use django.utils.six instead (#282)
* Drop six requirement, use django.utils.six instead

* Drop six requirement, use django.utils.six instead

* Make isort happy
2016-06-19 12:27:49 +02:00
Johannes Hoppe
57dfd53d55 Bump version number 2016-05-23 16:18:39 +02:00
Johannes Hoppe
f943fe07f5 Fixes #256 -- Don't render empty option for multiselect (#275) 2016-05-23 16:17:31 +02:00
AppleGrew
a6a12d7392 Doc link's domain name updated 2016-04-28 13:12:16 +05:30
Johannes Hoppe
f579f4af35 Adds travis-ci auto deploy 2016-04-22 15:25:04 +02:00
Julian
0b3abb8f1f Fixes minor documentation typo 2016-04-03 13:20:53 +02:00
53 changed files with 1432 additions and 1581 deletions

2
.bandit Normal file
View file

@ -0,0 +1,2 @@
[bandit]
exclude: tests

20
.editorconfig Normal file
View file

@ -0,0 +1,20 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
charset = utf-8
end_of_line = lf
[*.{json,yml,yaml,js,jsx}]
indent_size = 2
[LICENSE]
insert_final_newline = false
[Makefile]
indent_style = tab

4
.fussyfox.yml Normal file
View file

@ -0,0 +1,4 @@
- bandit
- flake8
- isort
- pydocstyle

2
.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1,2 @@
github: codingjoe
custom: https://paypal.me/codingjoe

30
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View file

@ -0,0 +1,30 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: codingjoe
---
**Describe the bug**
A clear and concise description of what the bug is.
**Exception & Traceback**
Should you have run into an exception, please provide us with the exception as well as with the full traceback.
**Code Snippet**
Please provide us with a code example on how to reproduce the error.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.

View file

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View file

@ -0,0 +1,13 @@
---
name: Problem with Django admin
about: You are facing a problem integrating django-select2 into Django's admin interface
title: ''
labels: wontfix
assignees: ''
---
Django-Select2 does NOT support Django admin, since Django admin has a built-in feature called `autocomplete_fields`. Autocomplete fields are superior and we recommend using them, instead of this package for the admin.
You can find more information here:
https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields

17
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View file

@ -0,0 +1,17 @@
---
name: Question
about: You have a question about Django-Select2
title: ''
labels: question
assignees: ''
---
**Goal**
Please describe your goal in all detail. What are you trying to do
**Problem**
Please describe your problem in all detail. Where are you struggling?
**Code Snippet**
Please provide a code snippet of your problem.

10
.gitignore vendored
View file

@ -1,6 +1,3 @@
testapp/tt.py
*.pyc
Django_Select2.egg-info
@ -19,3 +16,10 @@ docs/_build
env/
venv/
.cache/
.tox/
geckodriver.log
ghostdriver.log
.coverage
coverage.xml
.eggs/

View file

@ -1,44 +1,87 @@
language: python
sudo: false
cache:
- apt
- pip
services:
- memcached
dist: xenial
python:
- "2.7"
- "3.4"
- "3.5"
addons:
apt:
packages:
- python3-enchant
- python2-enchant
- graphviz
- "3.6"
- "3.7"
- "3.8"
env:
global:
- 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=22
- DJANGO=30
- DJANGO=master
matrix:
fast_finish: true
allow_failures:
- 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
script:
- 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
- env: DJANGO=master
addons:
apt:
packages:
- chromium-chromedriver
install: pip install tox-travis codecov
before_script:
- ln -s /usr/lib/chromium-browser/chromedriver ~/bin/chromedriver
- |
if [[ -z $TOXENV ]]; then
export TOXENV=py$(echo $TRAVIS_PYTHON_VERSION | sed -e 's/\.//g')-dj$DJANGO
fi
- echo $TOXENV
script: tox
after_success: codecov
stages:
- test
- name: deploy
if: tag is present
jobs:
include:
- python: "3.7"
env: TOXENV=docs
addons:
apt:
packages:
- python3-enchant
- python-enchant
- graphviz
- language: node_js
addons: {}
install: npm install
script: npm test
node_js: lts/*
cache: npm
- stage: deploy
python: "3.8"
install: skip
script: skip
after_success: true
deploy:
provider: pypi
distributions: sdist bdist_wheel
on:
tags: true
user: codingjoe
password:
secure: fEP9K7y0ZF9fRvQEUN4kgPXQEZvi3Cx3ikUebG2UM/2uhcaUQm0+KpgZ2S+lvOTYcBnNgzPzFsVIZMcVcTxwIKuQDEMq9y2eop2hnisb9KXsIm9qPYSzOnRm74VuiOt4hNOZMe0qVBK2cO3vC9NDXuzdI8A0JynJhthfl4t+kFM=
- stage: deploy
language: node_js
node_js: lts/*
python: "3.8"
install: skip
script: skip
after_success: true
skip_cleanup: true
before_deploy:
- ./set_version.py
deploy:
provider: npm
on:
tags: true
email: info@johanneshoppe.com
api_key:
secure: PV38cQx9qhEFkpSdytbM72UzIMCfhpjmRJ8dzT+bCAaOIs5rEcyKN+h1r5ranunCxWyuFsMW4A2iW/SCxnKCR/oPAguuwUbT5ogBXlsskqPFWUxuoTHYMrd+zB+SC6+bMgq+o5ul+kJCYtEkWP6cMlIEzKyTLab7m5PsnDXNVnI=

View file

@ -1,185 +0,0 @@
Changelog Summary
=================
### 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.
Prior to that change you could use any `field_id` on any select2 JSON endpoint.
Even if the id was intended to be used on a private endpoint if could be used on
the default one and therefore leak sensitive data.
* Breaking change on how `Heavy` widgets are being cached.
Heavy widgets used to add themselves to the cache. Now they add a dictionary to
the cache containing themselves and the target url.
```python
{
'widget': self,
'url': self.get_url(),
}
```
### v5.6.0
* Added `label_from_instance` method for model widgets to define custom option labels.
### v5.5.0
* Added settings to delivery static assets from different source.
### v5.4.2
* Fixed initial data not being shown for heavy widgets.
### v5.4.1
* Fixed memory leak in `ModelSelect2Mixin` and subclasses
### v5.4.0
* Added `Select2TagWidget` a light widget with tagging support
### v5.3.0
* Added djangoSelect2 jQuery plugin to support
dynamic field initialisation
### v5.2.0
* Added pagination
### v5.1.0
* Added search term splitting
* Model widgets get smarter pickling to reduce size and avoid pickling issues
### v5.0.0
Version 5 is a complete rewrite of the package to drastically reduce
the code base and to ensure a future maintainability.
While we feature set remained unchanged, the API changed completely.
Major changes:
* Fields have been removed in favor of widgets.
* All version 4 settings have been removed.
* Template tags have been removed.
* 3rd party javascript is served by a CDN.
* No more inline javascript code.
### v4.3.2
* Use `django.contrib.staticfiles.templatetags.staticfiles.static` over `django.templatetags.static.static` to allow hashing.
* Py23 unicode fixes
### v4.3.1
* Build failure fix.
### v4.3.0
* Now the package supports both Python2 and Python3.
* Django 1.8 support added.
* Many bug fixes.
### v4.2.2
* Misc fixes and enhancements - [61](https://github.com/applegrew/django-select2/pull/61), [64](https://github.com/applegrew/django-select2/issues/64).
### v4.2.1
* Finally fixed performance issue[#54](https://github.com/applegrew/django-select2/issues/54) (and issue[#41](https://github.com/applegrew/django-select2/issues/41)) in widgets when backing field is based on models and the field has an initial value.
### v4.2.0
* Updated Select2 to version 3.4.2. **Please note**, that if you need any of the Select2 locale files, then you need to download them yourself from http://ivaynberg.github.com/select2/ and add to your project.
* Tagging support added. See [Field API reference](http://django-select2.readthedocs.org/en/latest/ref_fields.html) in documentation.
### v4.1.0
* Updated Select2 to version 3.4.1. **Please note**, that if you need any of the Select2 locale files, then you need to download them yourself from http://ivaynberg.github.com/select2/ and add to your project.
* Address isssue[#36](https://github.com/applegrew/django-select2/issues/36) - Fix importerror under django1.6.
* Fixed the way `setup.py` handles Unicode files while minifying them during package build.
* Address isssue[#39](https://github.com/applegrew/django-select2/issues/39) - MultipleSelect2HiddenInput.render() should use mark_safe().
* Address isssue[#45](https://github.com/applegrew/django-select2/issues/45) - MultipleSelect2HiddenInput returns bad has_changed value.
### v4.0.0
* Main version number bumped to bring your attention to the fact that the default Id generation scheme has now changed. Now Django Select2 will use hashed paths of fields to generate their Ids. The old scheme of generating random Ids are still there. You can enable that by setting `GENERATE_RANDOM_SELECT2_ID` to `True`.
### v3.3.1
* Addressed issue[#30](https://github.com/applegrew/django-select2/issues/30).
* Merged pull request[#31](https://github.com/applegrew/django-select2/issues/31).
* Added `light` parameter to `import_django_select2_js`, `import_django_select2_css` and `import_django_select2_js_css` template tags. Please see doc's "Getting Started", for more details.
### v3.3.0
* Updated Select2 to version 3.3.1.
* Added multi-process support. ([Issue#28](https://github.com/applegrew/django-select2/issues/28)).
* Addressed issue[#26](https://github.com/applegrew/django-select2/issues/26).
* Addressed issue[#24](https://github.com/applegrew/django-select2/issues/24).
* Addressed issue[#23](https://github.com/applegrew/django-select2/issues/23).
* Addressed some typos.
### v3.2.0
* Fixed issue[#20](https://github.com/applegrew/django-select2/issues/20). Infact while fixing that I realised that heavy components do not need the help of cookies, infact due to a logic error in previous code the cookies were not being used anyway. Now Django Select2 does not use cookies etc.
* Few more bugs fixed in `heav_data.js`.
* Now production code will use minimized versions of js and css files.
* Codes added in `setup.py` to automate the task of minimizing js and css files, using a web service.
### v3.1.5
* Merged pull request (issue[#17](https://github.com/applegrew/django-select2/issues/17)). Which allows the user to pass some extra data to Select2 clients-side component.
* Updated License. The previous one was inadequently worded. Now this project use Apache 2.0 license.
### v3.1.4
* Manually merged changes from pull request (issue[#16](https://github.com/applegrew/django-select2/issues/16)).
* Django Select2 widgets now allow passing of any Select2 Js options. Previously it used to allow only white-listed options. Now it will block only black-listed options. For example, Light Select2 widgets won't allow you to set `multiple` option, since it is an error to set them when Select2 Js is bound to `<select>` fields.
### v3.1.3
* Addressed enhancement issue[#12](https://github.com/applegrew/django-select2/issues/12).
* Addressed enhancement issue[#11](https://github.com/applegrew/django-select2/issues/11).
* Addressed performance issue[#8](https://github.com/applegrew/django-select2/issues/8).
### v3.1.2
* Fixed issue[#7](https://github.com/applegrew/django-select2/issues/7).
### v3.1.1
* Bumping up minor version since Select2 JS has been updated to version 3.2. It seems Select2 JS now includes new higher resolution icons for [Retina displays](http://en.wikipedia.org/wiki/Retina_Display).
* Fixed an issue in `setup.py` because of which `templatetags` directory was not included in last PIP releases' tar file.
### v3.0.2
* Added `AUTO_RENDER_SELECT2_STATICS` settings. This, when specified and set to `False` in `settings.py` then Django_Select2 widgets won't automatically include the required scripts and stylesheets. When this setting is `True` (default) then every Select2 field on the page will output `<script>` and `<link>` tags to include the required JS and CSS files. This is convinient but will output the same JS and CSS files multiple times if there are more than one Select2 fields on the page.
* Added `django_select2_tags` template tags to manually include the required JS and CSS files, when `AUTO_RENDER_SELECT2_STATICS` is turned off.
### v3.0.1
* Revised the design of heavy fields. The previous design didn't quite make it easy to back heavy fields by big data sources. See `fields.HeavyChoiceField` class and its methods' docs for more info.
* Updated docs.
* Some more fixes for issue[#4](https://github.com/applegrew/django-select2/issues/4).
* Updated Select2 JS to version 3.1.
### v3.0
* Added docs.
* Some bug fixes. See issue[#4](https://github.com/applegrew/django-select2/issues/4).
* `widgets.Select2Mixin.__init__` now accepts `select2_options` kwarg to override its `options` settings. Previously `attrs` were being used for this too. This means backward compatibility has been broken here. `attrs` will no longer override `options` values. **The major release version has been changed to 3, because of this backward incompatible change.**
### v2.0.1
* Auto id registration fixes.
### v2.0
* Mostly major bug fixes in code and design. The changes were many, raising the possibility of backward incompatibility. However, the backward incompatibility would be subtle.
* Auto fields (sub-classes of AutoViewFieldMixin) now accepts `auto_id` parameter. This can be used to provide custom id for the field. The default is 'module.field_class_name'. Ideally only the first instance of an auto field is registered. This parameter can be used to force registration of additional instances by passing a unique value.

22
CONTRIBUTING.rst Normal file
View file

@ -0,0 +1,22 @@
Contributing
============
This package uses the pyTest test runner. To run the tests locally simply run::
python setup.py test
If you need to the development dependencies installed of you local IDE, you can run::
python setup.py develop
Documentation pull requests welcome. The Sphinx documentation can be compiled via::
python setup.py build_sphinx
Bug reports welcome, even more so if they include a correct patch. Much
more so if you start your patch by adding a failing unit test, and correct
the code until zero unit tests fail.
The list of supported Django and Python version can be found in the CI suite setup.
Please make sure to verify that none of the linters or tests failed, before you submit
a patch for review.

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Johannes Hoppe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View file

@ -1,5 +1,6 @@
include *.txt *.md
recursive-include django_select2/static *.*
recursive-exclude django_select2/static .DS_Store
exclude requirements_dev.txt
include django_select2/static/django_select2/django_select2.js
prune tests
prune .github
exclude .fussyfox.yml
exclude .travis.yml
exclude .gitignore

100
README.md
View file

@ -1,100 +0,0 @@
Django-Select2
==============
[![PyPi Version](https://img.shields.io/pypi/v/Django-Select2.svg)](https://pypi.python.org/pypi/Django-Select2/)
[![Build Status](https://travis-ci.org/applegrew/django-select2.svg?branch=master)](https://travis-ci.org/applegrew/django-select2)
[![Test Coverage](https://coveralls.io/repos/applegrew/django-select2/badge.svg?branch=master)](https://coveralls.io/r/applegrew/django-select2)
[![GitHub license](https://img.shields.io/badge/license-APL2-blue.svg)](https://raw.githubusercontent.com/applegrew/django-select2/master/LICENSE.txt)
[![Join the chat at https://gitter.im/applegrew/django-select2](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/applegrew/django-select2?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
This is a [Django](https://www.djangoproject.com/) integration of [Select2](http://ivaynberg.github.com/select2/).
The app includes Select2 driven Django Widgets.
## Installation
1. Install `django_select2`
pip install django_select2
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.
url(r'^select2/', include('django_select2.urls')),
### Upgrade from Version 4
Version 5 is a complete rewrite of the package to drastically reduce
the code base and to ensure a future maintainability.
While we feature set remained unchanged, the API changed completely.
Major changes:
- Fields have been removed in favor of widgets.
- All version 4 settings have been removed.
- Template tags have been removed.
- 3rd party javascript is served by a CDN.
- No more inline javascript code.
#### Upgrade can be done in 5 simple steps:
1. Remove all existing and to setup the new cache backend.
2. Remove the old template tags from your templates:
1. `import_django_select2_js`
2. `import_django_select2_css`
3. `import_django_select2_js_css`
3. Add `form.media.css` to the top and `form.media.js`
to the bottom of your base template.
4. Upgrade to jQuery version 2, if you are still running version 1.
5. Replace old fields with new widgets.
## Documentation
Documentation available at http://django-select2.readthedocs.org/.
## External Dependencies
* jQuery version 2
This is not included in the package since it is expected
that in most scenarios this would already be available.
## Example Application
Please see `tests/testapp` application.
This application is used to manually test the functionalities of this package.
This also serves as a good example.
## Special Thanks
* Samuel Goldszmidt (@ouhouhsami) for reporting many fundamental issues with the code, because of which versions 2.0 and 2.0.1 were released.
## Official Contributors
* Johannes Hoppe (@codingjoe)
## Changelog
See [CHANGELOG.md](CHANGELOG.md)
## License
Copyright 2012 Nirupam Biswas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this project except in compliance with the License.
You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

69
README.rst Normal file
View file

@ -0,0 +1,69 @@
Django-Select2
==============
|version| |ci| |coverage| |license|
This is a `Django`_ integration of `Select2`_.
The app includes Select2 driven Django Widgets.
.. note::
Django's admin comes with builtin support for Select2
since version 2.0 via the `autocomplete_fields`_ feature.
Installation
------------
1. Install ``django_select2``
.. code:: python
pip install django_select2
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.
.. code:: python
url(r'^select2/', include('django_select2.urls')),
Documentation
-------------
Documentation available at http://django-select2.readthedocs.io/.
External Dependencies
---------------------
- jQuery version 2 This is not included in the package since it is
expected that in most scenarios this would already be available.
Example Application
-------------------
Please see ``tests/testapp`` application. This application is used to
manually test the functionalities of this package. This also serves as a
good example.
Changelog
---------
See `Github releases`_
.. _Django: https://www.djangoproject.com/
.. _Select2: http://ivaynberg.github.com/select2/
.. _autocomplete_fields: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields
.. _CHANGELOG.md: CHANGELOG.md
.. _Github releases: https://github.com/applegrew/django-select2/releases
.. |version| image:: https://img.shields.io/pypi/v/Django-Select2.svg
:target: https://pypi.python.org/pypi/Django-Select2/
.. |ci| image:: https://travis-ci.org/applegrew/django-select2.svg?branch=master
:target: https://travis-ci.org/applegrew/django-select2
.. |coverage| image:: https://codecov.io/gh/applegrew/django-select2/branch/master/graph/badge.svg
:target: https://codecov.io/gh/applegrew/django-select2
.. |license| image:: https://img.shields.io/badge/license-APL2-blue.svg
:target: https://raw.githubusercontent.com/applegrew/django-select2/master/LICENSE.txt

View file

@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-
"""
This is a Django_ integration of Select2_.
The app includes Select2 driven Django Widgets and Form Fields.
The application includes Select2 driven Django Widgets and Form Fields.
.. _Django: https://www.djangoproject.com/
.. _Select2: http://ivaynberg.github.com/select2/
"""
__version__ = "5.8.4"
default_app_config = 'django_select2.apps.Select2AppConfig'

9
django_select2/apps.py Normal file
View file

@ -0,0 +1,9 @@
"""Django application configuration."""
from django.apps import AppConfig
class Select2AppConfig(AppConfig):
"""Django application configuration."""
name = 'django_select2'
verbose_name = 'Select2'

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Shared memory across multiple machines to the heavy AJAX lookups.
@ -12,8 +11,6 @@ It is advised to always setup a separate cache server for Select2.
.. _django.core.cache: https://docs.djangoproject.com/en/dev/topics/cache/
"""
from __future__ import absolute_import, unicode_literals
from django.core.cache import caches
from .conf import settings

View file

@ -1,7 +1,4 @@
# -*- coding: utf-8 -*-
"""Settings for Django-Select2."""
from __future__ import absolute_import, unicode_literals
from appconf import AppConf
from django.conf import settings # NOQA
@ -11,6 +8,9 @@ __all__ = ('settings', 'Select2Conf')
class Select2Conf(AppConf):
"""Settings for Django-Select2."""
LIB_VERSION = '4.0.12'
"""Version of the Select2 library."""
CACHE_BACKEND = 'default'
"""
Django-Select2 uses Django's cache to sure a consistent state across multiple machines.
@ -26,8 +26,11 @@ class Select2Conf(AppConf):
}
},
'select2': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
@ -37,18 +40,23 @@ class Select2Conf(AppConf):
.. tip:: To ensure a consistent state across all you machines you need to user
a consistent external cache backend like Memcached, Redis or a database.
.. note::
Should you have copied the example configuration please make sure you
have Redis setup. It's recommended to run a separate Redis server in a
production environment.
.. note:: The timeout of select2's caching backend determines
how long a browser session can last.
Once widget is dropped from the cache the json response view will return a 404.
"""
CACHE_PREFIX = 'select2_'
"""
If you caching backend doesn't support multiple databases
If you caching backend does not support multiple databases
you can isolate select2 using the cache prefix setting.
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/{version}/js/select2.min.js'.format(version=LIB_VERSION)
"""
The URI for the Select2 JS file. By default this points to the Cloudflare CDN.
@ -57,11 +65,16 @@ class Select2Conf(AppConf):
SELECT2_JS = 'assets/js/select2.min.js'
If you provide your own JS and would not like Django-Select2 to load any, change
this setting to a blank string like so::
SELECT2_JS = ''
.. tip:: Change this setting to a local asset in your development environment to
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/{version}/css/select2.min.css'.format(version=LIB_VERSION)
"""
The URI for the Select2 CSS file. By default this points to the Cloudflare CDN.
@ -70,9 +83,98 @@ class Select2Conf(AppConf):
SELECT2_CSS = 'assets/css/select2.css'
If you provide your own CSS and would not like Django-Select2 to load any, change
this setting to a blank string like so::
SELECT2_CSS = ''
.. tip:: Change this setting to a local asset in your development environment to
develop without an Internet connection.
"""
I18N_PATH = '//cdnjs.cloudflare.com/ajax/libs/select2/{version}/js/i18n'.format(version=LIB_VERSION)
"""
The base URI for the Select2 i18n files. By default this points to the Cloudflare CDN.
If you want to select the version of the I18N library used, or want to serve it from
the local 'static' resources, add a line to your settings.py like so::
SELECT2_I18N_PATH = 'assets/js/i18n'
.. tip:: Change this setting to a local asset in your development environment to
develop without an Internet connection.
"""
I18N_AVAILABLE_LANGUAGES = [
'ar',
'az',
'bg',
'ca',
'cs',
'da',
'de',
'el',
'en',
'es',
'et',
'eu',
'fa',
'fi',
'fr',
'gl',
'he',
'hi',
'hr',
'hu',
'id',
'is',
'it',
'ja',
'km',
'ko',
'lt',
'lv',
'mk',
'ms',
'nb',
'nl',
'pl',
'pt-BR',
'pt',
'ro',
'ru',
'sk',
'sr-Cyrl',
'sr',
'sv',
'th',
'tr',
'uk',
'vi',
'zh-CN',
'zh-TW',
]
"""
List of available translations.
List of ISO 639-1 language codes that are supported by Select2.
If currently set language code (e.g. using the HTTP ``Accept-Language`` header)
is in this list, Django-Select2 will use the language code to create load
the proper translation.
The full path for the language file consists of::
from django.utils import translations
full_path = "{i18n_path}/{language_code}.js".format(
i18n_path=settings.DJANGO_SELECT2_I18N,
language_code=translations.get_language(),
)
``settings.DJANGO_SELECT2_I18N`` refers to :attr:`.I18N_PATH`.
"""
class Meta:
"""Prefix for all Django-Select2 settings."""
prefix = 'SELECT2'

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Django-Select2 Widgets.
@ -21,10 +20,11 @@ Widgets are generally of two types:
drop-in-replacement for Django's default
select widgets.
2. **Heavy** --
2(a). **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,
@ -32,40 +32,37 @@ Widgets are generally of two types:
Although on the server side you do need to create a view
specifically to respond to the queries.
3. **Model** --
2(b). **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.
Heavy and Model widgets have respectively the word 'Heavy' and 'Model' 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 __future__ import absolute_import, unicode_literals
from functools import reduce
from itertools import chain
from pickle import PicklingError
from pickle import PicklingError # nosec
from django import forms
from django.contrib.admin.widgets import SELECT2_TRANSLATIONS
from django.core import signing
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 six.moves.cPickle import PicklingError as cPicklingError
from django.urls import reverse
from django.utils.translation import get_language
from .cache import cache
from .conf import settings
class Select2Mixin(object):
class Select2Mixin:
"""
The base mixin of all Select2 widgets.
@ -74,52 +71,69 @@ class Select2Mixin(object):
form media.
"""
def build_attrs(self, extra_attrs=None, **kwargs):
"""Add select2 data attributes."""
attrs = super(Select2Mixin, self).build_attrs(extra_attrs=extra_attrs, **kwargs)
if self.is_required:
attrs.setdefault('data-allow-clear', 'false')
else:
attrs.setdefault('data-allow-clear', 'true')
attrs.setdefault('data-placeholder', '')
empty_label = ''
def build_attrs(self, base_attrs, extra_attrs=None):
"""Add select2 data attributes."""
default_attrs = {'data-minimum-input-length': 0}
if self.is_required:
default_attrs['data-allow-clear'] = 'false'
else:
default_attrs['data-allow-clear'] = 'true'
default_attrs['data-placeholder'] = self.empty_label or ""
default_attrs.update(base_attrs)
attrs = super().build_attrs(default_attrs, extra_attrs=extra_attrs)
attrs.setdefault('data-minimum-input-length', 0)
if 'class' in attrs:
attrs['class'] += ' django-select2'
else:
attrs['class'] = 'django-select2'
return attrs
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(*args, **kwargs)
return output
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)
def _get_media(self):
"""
Construct Media as a dynamic property.
.. Note:: For more information visit
https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property
https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
"""
lang = get_language()
select2_js = (settings.SELECT2_JS,) if settings.SELECT2_JS else ()
select2_css = (settings.SELECT2_CSS,) if settings.SELECT2_CSS else ()
i18n_name = SELECT2_TRANSLATIONS.get(lang)
if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
i18n_name = None
i18n_file = ('%s/%s.js' % (settings.SELECT2_I18N_PATH, i18n_name),) if i18n_name else ()
return forms.Media(
js=(settings.SELECT2_JS, 'django_select2/django_select2.js'),
css={'screen': (settings.SELECT2_CSS,)}
js=select2_js + i18n_file + ('django_select2/django_select2.js',),
css={'screen': select2_css}
)
media = property(_get_media)
class Select2TagMixin(object):
class Select2TagMixin:
"""Mixin to add select2 tag functionality."""
def build_attrs(self, extra_attrs=None, **kwargs):
def build_attrs(self, base_attrs, extra_attrs=None):
"""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(extra_attrs, **kwargs)
default_attrs = {
'data-minimum-input-length': 1,
'data-tags': 'true',
'data-token-separators': '[",", " "]'
}
default_attrs.update(base_attrs)
return super().build_attrs(default_attrs, extra_attrs=extra_attrs)
class Select2Widget(Select2Mixin, forms.Select):
@ -168,29 +182,52 @@ class Select2TagWidget(Select2TagMixin, Select2Mixin, forms.SelectMultiple):
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
class HeavySelect2Mixin(object):
class HeavySelect2Mixin:
"""Mixin that adds select2's AJAX options and registers itself on Django's cache."""
def __init__(self, **kwargs):
dependent_fields = {}
def __init__(self, attrs=None, choices=(), **kwargs):
"""
Return HeavySelect2Mixin.
Args:
data_view (str): URL pattern name
data_url (str): URL
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`).
"""
self.choices = choices
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
self.data_view = kwargs.pop('data_view', None)
self.data_url = kwargs.pop('data_url', None)
dependent_fields = kwargs.pop('dependent_fields', None)
if dependent_fields is not None:
self.dependent_fields = dict(dependent_fields)
if not (self.data_view or self.data_url):
raise ValueError('You must ether specify "data_view" or "data_url".')
self.userGetValTextFuncName = kwargs.pop('userGetValTextFuncName', 'null')
super(HeavySelect2Mixin, self).__init__(**kwargs)
def get_url(self):
"""Return URL from instance or by reversing :attr:`.data_view`."""
@ -198,18 +235,26 @@ class HeavySelect2Mixin(object):
return self.data_url
return reverse(self.data_view)
def build_attrs(self, extra_attrs=None, **kwargs):
def build_attrs(self, base_attrs, extra_attrs=None):
"""Set select2's AJAX attributes."""
attrs = super(HeavySelect2Mixin, self).build_attrs(extra_attrs=extra_attrs, **kwargs)
default_attrs = {
'data-ajax--url': self.get_url(),
'data-ajax--cache': "true",
'data-ajax--type': "GET",
'data-minimum-input-length': 2,
}
if self.dependent_fields:
default_attrs['data-select2-dependent-fields'] = " ".join(self.dependent_fields)
default_attrs.update(base_attrs)
attrs = super().build_attrs(default_attrs, extra_attrs=extra_attrs)
# encrypt instance Id
self.widget_id = signing.dumps(id(self))
attrs['data-field_id'] = self.widget_id
attrs.setdefault('data-ajax--url', self.get_url())
attrs.setdefault('data-ajax--cache', "true")
attrs.setdefault('data-ajax--type', "GET")
attrs.setdefault('data-minimum-input-length', 2)
attrs['class'] += ' django-select2-heavy'
return attrs
@ -235,26 +280,10 @@ class HeavySelect2Mixin(object):
'widget': self,
'url': self.get_url(),
})
except (PicklingError, cPicklingError, AttributeError):
except (PicklingError, 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."""
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 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, Select2Widget):
"""
@ -262,14 +291,14 @@ class HeavySelect2Widget(HeavySelect2Mixin, Select2Widget):
Usage example::
class MyWidget(HeavySelectWidget):
class MyWidget(HeavySelect2Widget):
data_view = 'my_view_name'
or::
class MyForm(forms.Form):
my_field = forms.ChoicesField(
widget=HeavySelectWidget(
my_field = forms.ChoiceField(
widget=HeavySelect2Widget(
data_url='/url/to/json/response'
)
)
@ -294,7 +323,7 @@ class HeavySelect2TagWidget(HeavySelect2Mixin, Select2TagWidget):
# Auto Heavy widgets
class ModelSelect2Mixin(object):
class ModelSelect2Mixin:
"""Widget mixin that provides attributes and methods for :class:`.AutoResponseView`."""
model = None
@ -314,13 +343,19 @@ class ModelSelect2Mixin(object):
max_results = 25
"""Maximal results returned by :class:`.AutoResponseView`."""
@property
def empty_label(self):
if isinstance(self.choices, ModelChoiceIterator):
return self.choices.field.empty_label
return ''
def __init__(self, *args, **kwargs):
"""
Overwrite class parameters if passed as keyword arguments.
Args:
model (django.db.models.Model): Model to select choices from.
queryset (django.db.models.QuerySet): QuerySet to select choices from.
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.
@ -329,7 +364,7 @@ class ModelSelect2Mixin(object):
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)
defaults = {'data_view': 'django_select2-json'}
defaults = {'data_view': 'django_select2:auto-json'}
defaults.update(kwargs)
super(ModelSelect2Mixin, self).__init__(*args, **defaults)
@ -347,17 +382,24 @@ class ModelSelect2Mixin(object):
queryset.query,
],
'cls': self.__class__,
'search_fields': self.search_fields,
'max_results': self.max_results,
'url': self.get_url(),
'search_fields': tuple(self.search_fields),
'max_results': int(self.max_results),
'url': str(self.get_url()),
'dependent_fields': dict(self.dependent_fields),
})
def filter_queryset(self, term, queryset=None):
def filter_queryset(self, request, term, queryset=None, **dependent_fields):
"""
Return QuerySet filtered by search_fields matching the passed term.
Args:
request (django.http.request.HttpRequest): The request is being passed from
the JSON view and can be used to dynamically alter the response queryset.
term (str): Search term
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
@ -370,8 +412,11 @@ class ModelSelect2Mixin(object):
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,
select &= reduce(lambda x, y: x | Q(**{y: t}), search_fields[1:],
Q(**{search_fields[0]: t}))
if dependent_fields:
select &= Q(**dependent_fields)
return queryset.filter(select).distinct()
def get_queryset(self):
@ -384,6 +429,8 @@ class ModelSelect2Mixin(object):
"""
if self.queryset is not None:
queryset = self.queryset
elif hasattr(self.choices, 'queryset'):
queryset = self.choices.queryset
elif self.model is not None:
queryset = self.model._default_manager.all()
else:
@ -402,29 +449,36 @@ class ModelSelect2Mixin(object):
return self.search_fields
raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__)
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 else '']
if isinstance(self.choices, ModelChoiceIterator):
if not self.queryset:
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 = {(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)
def optgroups(self, name, value, attrs=None):
"""Return only selected options and set QuerySet from `ModelChoicesIterator`."""
default = (None, [], 0)
groups = [default]
has_selected = False
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 = (
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):
"""
@ -436,7 +490,7 @@ class ModelSelect2Mixin(object):
class MyWidget(ModelSelect2Widget):
def label_from_instance(obj):
return force_text(obj.title).upper()
return str(obj.title).upper()
Args:
obj (django.db.models.Model): Instance of Django Model.
@ -445,7 +499,7 @@ class ModelSelect2Mixin(object):
str: Option label.
"""
return force_text(obj)
return str(obj)
class ModelSelect2Widget(ModelSelect2Mixin, HeavySelect2Widget):
@ -510,14 +564,15 @@ class ModelSelect2TagWidget(ModelSelect2Mixin, HeavySelect2TagWidget):
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)})
pks = set(force_text(getattr(o, pk)) for o in qs)
cleaned_values = []
for val in value:
if force_text(val) not in pks:
val = queryset.create(title=val).pk
cleaned_values.append(val)
'''Create objects for given non-pimary-key values. Return list of all primary keys.'''
values = set(super().value_from_datadict(data, files, name))
# This may only work for MyModel, if MyModel has title field.
# You need to implement this method yourself, to ensure proper object creation.
pks = self.queryset.filter(**{'pk__in': list(values)}).values_list('pk', flat=True)
pks = set(map(str, pks))
cleaned_values = list(values)
for val in values - pks:
cleaned_values.append(self.queryset.create(title=val).pk)
return cleaned_values
"""

View file

@ -1 +0,0 @@
"""Django legacy file."""

View file

@ -1,48 +1,69 @@
(function ($) {
/* global define, jQuery */
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory)
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(require('jquery'))
} else {
// Browser globals
factory(jQuery)
}
}(function ($) {
'use strict'
var init = function ($element, options) {
$element.select2(options)
}
var init = function ($element, options) {
$element.select2(options);
};
var initHeavy = function ($element, options) {
var settings = $.extend({
ajax: {
data: function (params) {
var result = {
term: params.term,
page: params.page,
field_id: $element.data('field_id')
}
var initHeavy = function ($element, options) {
var settings = $.extend({
ajax: {
data: function (params) {
return {
term: params.term,
page: params.page,
field_id: $element.data('field_id')
};
},
processResults: function (data, page) {
return {
results: data.results,
pagination: {
more: data.more
}
};
}
var dependentFields = $element.data('select2-dependent-fields')
if (dependentFields) {
dependentFields = dependentFields.trim().split(/\s+/)
$.each(dependentFields, function (i, dependentField) {
result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val()
})
}
return result
},
processResults: function (data, page) {
return {
results: data.results,
pagination: {
more: data.more
}
}, options);
}
}
}
}, options)
$element.select2(settings);
};
$element.select2(settings)
}
$.fn.djangoSelect2 = function (options) {
var settings = $.extend({}, options);
$.each(this, function (i, element) {
var $element = $(element);
if ($element.hasClass('django-select2-heavy')) {
initHeavy($element, settings);
} else {
init($element, settings);
}
});
return this;
};
$.fn.djangoSelect2 = function (options) {
var settings = $.extend({}, options)
$.each(this, function (i, element) {
var $element = $(element)
if ($element.hasClass('django-select2-heavy')) {
initHeavy($element, settings)
} else {
init($element, settings)
}
})
return this
}
$(function () {
$('.django-select2').djangoSelect2();
});
$(function () {
$('.django-select2').djangoSelect2()
})
}(this.jQuery));
return $.fn.djangoSelect2
}))

View file

@ -1,19 +1,20 @@
# -*- coding: utf-8 -*-
"""
Django-Select2 URL configuration.
Add `django_select` to your ``urlconf`` **if** you use any 'Model' fields::
url(r'^select2/', include('django_select2.urls')),
from django.urls import path
path('select2/', include('django_select2.urls')),
"""
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from django.urls import path
from .views import AutoResponseView
app_name = 'django_select2'
urlpatterns = [
url(r"^fields/auto.json$",
AutoResponseView.as_view(), name="django_select2-json"),
path("fields/auto.json", AutoResponseView.as_view(), name="auto-json"),
]

View file

@ -1,7 +1,4 @@
# -*- coding: utf-8 -*-
"""JSONResponse views for model widgets."""
from __future__ import absolute_import, unicode_literals
from django.core import signing
from django.core.signing import BadSignature
from django.http import Http404, JsonResponse
@ -52,7 +49,12 @@ class AutoResponseView(BaseListView):
def get_queryset(self):
"""Get QuerySet from cached widget."""
return self.widget.filter_queryset(self.term, self.queryset)
kwargs = {
model_field_name: self.request.GET.get(form_field_name)
for form_field_name, model_field_name in self.widget.dependent_fields.items()
if form_field_name in self.request.GET and self.request.GET.get(form_field_name, '') != ''
}
return self.widget.filter_queryset(self.request, self.term, self.queryset, **kwargs)
def get_paginate_by(self, queryset):
"""Paginate response by size of widget's `max_results` parameter."""

1
docs/CONTRIBUTING.rst Normal file
View file

@ -0,0 +1 @@
.. include:: ../CONTRIBUTING.rst

View file

@ -1,158 +0,0 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/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
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Django-Select2.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Django-Select2.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Django-Select2"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Django-Select2"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

View file

@ -1,302 +1,52 @@
# -*- coding: utf-8 -*-
#
# Django-Select2 documentation build configuration file, created by
# sphinx-quickstart on Sat Aug 25 10:23:46 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import datetime
import os
import sys
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
year = datetime.datetime.now().strftime("%Y")
# This is needed since django_select2 requires django model modules
# and those modules assume that django settings is configured and
# have proper DB settings.
# Using this we give a proper environment with working django settings.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.testapp.settings")
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../tests.testapp'))
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# 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.napoleon',
'sphinx.ext.inheritance_diagram',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinxcontrib.spelling',
]
intersphinx_mapping = {
'python': ('http://docs.python.org/3.5', None),
'django': ('https://docs.djangoproject.com/en/dev/',
'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']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Django-Select2'
copyright = u'%s, Nirupam Biswas' % year
def get_version():
import django_select2
return django_select2.__version__
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = get_version()
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
def skip(app, what, name, obj, skip, options):
if name == "__init__" and obj.__doc__:
return False
return skip
def setup(app):
app.connect("autodoc-skip-member", skip)
autodoc_default_flags = ['members', 'show-inheritance']
autodoc_member_order = 'bysource'
inheritance_graph_attrs = dict(rankdir='TB')
inheritance_node_attrs = dict(shape='rect', fontsize=14, fillcolor='gray90',
color='gray30', style='filled')
inheritance_edge_attrs = dict(penwidth=0.75)
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
if on_rtd:
html_theme = 'default'
else:
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Django-Select2doc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Django-Select2.tex', u'Django-Select2 Documentation',
u'Nirupam Biswas', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'django-select2', u'Django-Select2 Documentation',
[u'Nirupam Biswas'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Django-Select2', u'Django-Select2 Documentation',
u'Nirupam Biswas', 'Django-Select2', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
import os
import sys
from pkg_resources import get_distribution
# This is needed since django_select2 requires django model modules
# and those modules assume that django settings is configured and
# have proper DB settings.
# Using this we give a proper environment with working django settings.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.testapp.settings")
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../tests.testapp'))
sys.path.insert(0, os.path.abspath('..'))
project = "Django-Select2"
author = "Johannes Hoppe"
copyright = "2017, Johannes Hoppe"
release = get_distribution('django_select2').version
version = '.'.join(release.split('.')[:2])
master_doc = 'index' # default in Sphinx v2
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.inheritance_diagram',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx.ext.doctest',
]
intersphinx_mapping = {
'python': ('http://docs.python.org/3', None),
'django': ('https://docs.djangoproject.com/en/stable/',
'https://docs.djangoproject.com/en/stable/_objects/'),
}
autodoc_default_flags = ['members', 'show-inheritance']
autodoc_member_order = 'bysource'
inheritance_graph_attrs = dict(rankdir='TB')
inheritance_node_attrs = dict(shape='rect', fontsize=14, fillcolor='gray90',
color='gray30', style='filled')
inheritance_edge_attrs = dict(penwidth=0.75)

View file

@ -49,8 +49,9 @@ 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
heavy fields. Simply call ``djangoSelect2(options)`` on your select fields.::
yourself, DjangoSelect2 provides a jQuery plugin, replacing and enhancing the Select2
plugin. It will handle both normal and heavy fields. Simply call
``djangoSelect2(options)`` on your select fields.::
$('.django-select2').djangoSelect2();
@ -59,6 +60,9 @@ You can pass see `Select2 options <https://select2.github.io/options.html>`_ if
$('.django-select2').djangoSelect2({placeholder: 'Select an option'});
Please replace all your ``.select2`` invocations with the here provided
``.djangoSelect2``.
Security & Authentication
-------------------------
@ -81,6 +85,6 @@ want to be accessible to the general public. Doing so is easy::
kwargs['data_view'] = 'user-select2-view'
super(UserSelect2WidgetMixin, self).__init__(*args, **kwargs)
class MySecretWidget(UserSelect2WidgetMixin, Select2ModelWidget):
class MySecretWidget(UserSelect2WidgetMixin, ModelSelect2Widget):
model = MySecretModel
search_fields = ['title__icontains']

View file

@ -1,3 +0,0 @@
Django >= 1.8
sphinxcontrib-spelling
pyenchant

121
docs/extra.rst Normal file
View file

@ -0,0 +1,121 @@
Extra
=====
Chained select2
---------------
Suppose you have an address form where a user should choose a Country and a City.
When the user selects a country we want to show only cities belonging to that country.
So the one selector depends on another one.
Models
``````
Here are our two models:
.. code-block:: python
class Country(models.Model):
name = models.CharField(max_length=255)
class City(models.Model):
name = models.CharField(max_length=255)
country = models.ForeignKey('Country', related_name="cities")
Customizing a Form
``````````````````
Lets link two widgets via *dependent_fields*.
.. code-block:: python
:emphasize-lines: 15
class AddressForm(forms.Form):
country = forms.ModelChoiceField(
queryset=Country.objects.all(),
label=u"Country",
widget=ModelSelect2Widget(
model=Country,
search_fields=['name__icontains'],
)
)
city = forms.ModelChoiceField(
queryset=City.objects.all(),
label=u"City",
widget=ModelSelect2Widget(
model=City,
search_fields=['name__icontains'],
dependent_fields={'country': 'country'},
max_results=500,
)
)
Interdependent select2
----------------------
Also you may want not to restrict the user to which field should be selected first.
Instead you want to suggest to the user options for any select2 depending of his selection in another one.
Customize the form in a manner:
.. code-block:: python
:emphasize-lines: 7
class AddressForm(forms.Form):
country = forms.ModelChoiceField(
queryset=Country.objects.all(),
label=u"Country",
widget=ModelSelect2Widget(
search_fields=['name__icontains'],
dependent_fields={'city': 'cities'},
)
)
city = forms.ModelChoiceField(
queryset=City.objects.all(),
label=u"City",
widget=ModelSelect2Widget(
search_fields=['name__icontains'],
dependent_fields={'country': 'country'},
max_results=500,
)
)
Take attention to country's dependent_fields. The value of 'city' is 'cities' because of
related name used in a filter condition `cities` which differs from widget field name `city`.
.. caution::
Be aware of using interdependent select2 in parent-child relation.
When a child is selected, you are restricted to change parent (only one value is available).
Probably you should let the user reset the child first to release parent select2.
Multi-dependent select2
-----------------------
Furthermore you may want to filter options on two or more select2 selections (some code is dropped for clarity):
.. code-block:: python
:emphasize-lines: 14
class SomeForm(forms.Form):
field1 = forms.ModelChoiceField(
widget=ModelSelect2Widget(
)
)
field2 = forms.ModelChoiceField(
widget=ModelSelect2Widget(
)
)
field3 = forms.ModelChoiceField(
widget=ModelSelect2Widget(
dependent_fields={'field1': 'field1', 'field2': 'field2'},
)
)

View file

@ -8,6 +8,12 @@ Overview
.. automodule:: django_select2
:members:
Assumptions
-----------
* You have a running Django up and running.
* You have form fully working without Django-Select2.
Installation
------------
@ -17,19 +23,53 @@ Installation
2. Add ``django_select2`` to your ``INSTALLED_APPS`` in your project settings.
3. Add ``django_select`` to your ``urlconf``::
3. Add ``django_select`` to your ``urlconf`` **if** you use any
:class:`ModelWidgets <.django_select2.forms.ModelSelect2Mixin>`::
path('select2/', include('django_select2.urls')),
url(r'^select2/', include('django_select2.urls')),
You can safely skip this one if you do not use any
:class:`ModelWidgets <.django_select2.forms.ModelSelect2Mixin>`
Quick Start
-----------
Here is a quick example to get you started:
0. Follow the installation instructions above.
1. Replace native Django forms widgets with one of the several ``django_select2.form`` widgets.
Start by importing them into your ``forms.py``, right next to Django own ones::
from django import forms
from django_select2 import forms as s2forms
Then let's assume you have a model with a choice, a :class:`.ForeignKey`, and a
:class:`.ManyToManyField`, you would add this information to your Form Meta
class::
widgets = {
'category': s2forms.Select2Widget,
'author': s2forms.ModelSelect2Widget(model=auth.get_user_model(),
search_fields=['first_name__istartswith', 'last_name__icontains']),
'attending': s2forms.ModelSelect2MultipleWidget …
}
2. Add the CSS to the ``head`` of your Django template::
{{ form.media.css }}
3. Add the JavaScript to the end of the ``body`` of your Django template::
{{ form.media.js }}
4. Done - enjoy the wonders of Select2!
External Dependencies
---------------------
* jQuery version 2
This is not included in the package since it is expected
that in most scenarios this would already be available.
* jQuery (version >=2)
jQuery is not included in the package since it is expected
that in most scenarios jQuery is already loaded.
Example Application
-------------------

View file

@ -14,6 +14,8 @@ Contents:
get_started
django_select2
extra
CONTRIBUTING
Indices and tables
==================

View file

@ -1,190 +0,0 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Django-Select2.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Django-Select2.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end

View file

@ -15,3 +15,4 @@ functionalities
plugin
multi
Indices
clearable

37
package.json Normal file
View file

@ -0,0 +1,37 @@
{
"name": "django-select2",
"version": "0.0.0",
"description": "This is a Django integration of Select2.",
"files": [
"django_select2/static/**/*"
],
"main": "django_select2/static/django_select2/django_select2.js",
"directories": {
"doc": "docs",
"test": "tests"
},
"scripts": {
"test": "standard"
},
"repository": {
"type": "git",
"url": "git://github.com/applegrew/django-select2.git"
},
"keywords": [
"django",
"select2"
],
"author": "Johannes Hoppe",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/applegrew/django-select2/issues"
},
"homepage": "https://github.com/applegrew/django-select2#readme",
"peerDependencies": {
"select2": "*",
"jquery": ">= 1.2"
},
"devDependencies": {
"standard": "*"
}
}

View file

@ -1,12 +0,0 @@
django-appconf
flake8
pep8-naming
mccabe
isort
pep257
pytest
pytest-django
selenium
sphinx
sphinxcontrib-spelling
pyenchant

View file

@ -1,31 +0,0 @@
#
# This file is autogenerated by pip-compile
# Make changes in requirements_dev.in, then run this to update:
#
# pip-compile requirements_dev.in
#
alabaster==0.7.7 # via sphinx
babel==2.2.0 # via sphinx
django-appconf==1.0.1
docutils==0.12 # via sphinx
flake8==2.5.2
isort==4.2.2
Jinja2==2.8
MarkupSafe==0.23
mccabe==0.4.0
pep257==0.7.0
pep8-naming==0.3.3
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.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

12
set_version.py Executable file
View file

@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""Set the version in NPM's package.json to match the git tag."""
import json
import os
if __name__ == '__main__':
with open('package.json', 'r+') as f:
data = json.load(f)
f.seek(0)
data['version'] = os.environ['TRAVIS_TAG']
json.dump(data, f)
f.truncate()

View file

@ -1,22 +1,83 @@
[pytest]
norecursedirs = env
addopts = --tb=short -rxs
[metadata]
name = django-select2
author = Johannes Hoppe
author_email = info@johanneshoppe.com
description = Select2 option fields for Django
long_description = file: README.rst
url = https://github.com/applegrew/django-select2
license = MIT
license_file = LICENSE
classifier =
Development Status :: 5 - Production/Stable
Environment :: Web Environment
Intended Audience :: Developers
License :: OSI Approved :: Apache Software License
Operating System :: OS Independent
Programming Language :: Python
Programming Language :: Python :: 3
Framework :: Django
[options]
include_package_data = True
packages = django_select2
install_requires =
django>=2.2
django-appconf>=0.6.0
setup_requires =
setuptools_scm
sphinx
pytest-runner
tests_require =
pytest
pytest-cov
pytest-django
selenium
[bdist_wheel]
universal = 1
[bdist_rpm]
requires =
python-django-appconf >= 2.0
python-django-appconf >= 0.6
[aliases]
test = pytest
[build_sphinx]
source-dir = docs
build-dir = docs/_build
[tool:pytest]
addopts = --cov=django_select2 --cov-report xml
DJANGO_SETTINGS_MODULE=tests.testapp.settings
[tox:tox]
envlist = py{36,37,38}-dj{22,30,master},docs
[testenv]
passenv=CI
deps =
dj22: django~=2.2
dj30: django~=3.0
djmaster: https://github.com/django/django/archive/master.tar.gz#egg=django
commands = python setup.py test
[testenv:docs]
commands = python setup.py build_sphinx -W -b doctest -b html
[flake8]
max-line-length = 120
max-complexity = 10
statistics = true
show-source = true
exclude = docs,runtests.py,setup.py,env
[pep257]
[pydocstyle]
add_ignore = D1
[isort]
atomic = true
multi_line_output = 5
line_length = 79
skip = manage.py,docs
known_first_party = django_select2, tests
known_third_party = django
default_section=THIRDPARTY
combine_as_imports = true

View file

@ -1,53 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import codecs
import os
from setuptools import setup
from setuptools import Command, find_packages, setup
def read(file_name):
file_path = os.path.join(os.path.dirname(__file__), file_name)
return codecs.open(file_path, encoding='utf-8').read()
PACKAGE = "django_select2"
NAME = "Django-Select2"
DESCRIPTION = "Select2 option fields for Django"
AUTHOR = "Nirupam Biswas, Johannes Hoppe"
AUTHOR_EMAIL = "admin@applegrew.com"
URL = "https://github.com/applegrew/django-select2"
VERSION = __import__(PACKAGE).__version__
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=read("README.md"),
author=AUTHOR,
author_email=AUTHOR_EMAIL,
license="LICENSE.txt",
url=URL,
packages=find_packages(),
include_package_data=True,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Framework :: Django",
"Framework :: Django :: 1.8",
"Framework :: Django :: 1.9",
],
install_requires=[
'django-appconf>=0.6.0',
],
zip_safe=False,
)
setup(name='django-select2', use_scm_version=True)

View file

@ -1 +0,0 @@
__author__ = 'johannes'

View file

@ -1,7 +1,3 @@
# -*- coding:utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
import random
import string
@ -9,12 +5,6 @@ import pytest
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
browsers = {
# 'firefox': webdriver.Firefox,
# 'chrome': webdriver.Chrome,
'phantomjs': webdriver.PhantomJS,
}
def random_string(n):
return ''.join(
@ -23,20 +13,22 @@ def random_string(n):
)
@pytest.fixture(scope='session',
params=browsers.keys())
def driver(request):
if 'DISPLAY' not in os.environ:
pytest.skip('Test requires display server (export DISPLAY)')
def random_name(n):
words = ''.join(random.choice(string.ascii_lowercase + ' ') for _ in range(n)).strip().split(' ')
return '-'.join([x.capitalize() for x in words])
@pytest.yield_fixture(scope='session')
def driver():
chrome_options = webdriver.ChromeOptions()
chrome_options.headless = True
try:
b = browsers[request.param]()
b = webdriver.Chrome(options=chrome_options)
except WebDriverException as e:
pytest.skip(e)
pytest.skip(str(e))
else:
b.set_window_size(1200, 800)
request.addfinalizer(lambda *args: b.quit())
return b
yield b
b.quit()
@pytest.fixture
@ -54,3 +46,19 @@ def artists(db):
return Artist.objects.bulk_create(
[Artist(pk=pk, title=random_string(50)) for pk in range(100)]
)
@pytest.fixture
def countries(db):
from .testapp.models import Country
return Country.objects.bulk_create(
[Country(pk=pk, name=random_name(random.randint(10, 20))) for pk in range(10)]
)
@pytest.fixture
def cities(db, countries):
from .testapp.models import City
return City.objects.bulk_create(
[City(pk=pk, name=random_name(random.randint(5, 15)), country=random.choice(countries)) for pk in range(100)]
)

View file

@ -1,7 +1,3 @@
# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals
def test_default_cache():
from django_select2.cache import cache

View file

@ -1,18 +1,20 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import collections
import json
import os
from collections.abc import Iterable
import pytest
from django.core import signing
from django.core.urlresolvers import reverse
from django.db.models import QuerySet
from django.urls import reverse
from django.utils import translation
from django.utils.encoding import force_text
from selenium.common.exceptions import NoSuchElementException
from six import text_type
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from django_select2.cache import cache
from django_select2.conf import settings
from django_select2.forms import (
HeavySelect2MultipleWidget, HeavySelect2Widget, ModelSelect2TagWidget,
ModelSelect2Widget, Select2Widget
@ -21,18 +23,19 @@ from tests.testapp import forms
from tests.testapp.forms import (
NUMBER_CHOICES, HeavySelect2MultipleWidgetForm, TitleModelSelect2Widget
)
from tests.testapp.models import Genre
from tests.testapp.models import Artist, City, Country, Genre, Groupie
class TestSelect2Mixin(object):
class TestSelect2Mixin:
url = reverse('select2_widget')
form = forms.AlbumSelect2WidgetForm()
multiple_form = forms.AlbumSelect2MultipleWidgetForm()
widget_cls = Select2Widget
def test_initial_data(self, genres):
genre = genres[0]
form = self.form.__class__(initial={'primary_genre': genre.pk})
assert text_type(genre) in form.as_p()
assert str(genre) in form.as_p()
def test_initial_form_class(self):
widget = self.widget_cls(attrs={'class': 'my-class'})
@ -44,7 +47,7 @@ class TestSelect2Mixin(object):
assert required_field.required is True
assert 'data-allow-clear="true"' not in required_field.widget.render('artist', None)
assert 'data-allow-clear="false"' in required_field.widget.render('artist', None)
assert '<option></option>' not in required_field.widget.render('artist', None)
assert '<option value=""></option>' not in required_field.widget.render('artist', None)
not_required_field = self.form.fields['primary_genre']
assert not_required_field.required is False
@ -52,7 +55,7 @@ class TestSelect2Mixin(object):
assert 'data-allow-clear="false"' not in not_required_field.widget.render('primary_genre',
None)
assert 'data-placeholder' in not_required_field.widget.render('primary_genre', None)
assert '<option></option>' in not_required_field.widget.render('primary_genre', None)
assert '<option value=""></option>' in not_required_field.widget.render('primary_genre', None)
def test_no_js_error(self, db, live_server, driver):
driver.get(live_server + self.url)
@ -82,13 +85,71 @@ 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 value=""></option>' in single_select.widget.render('primary_genre', None)
class TestSelect2MixinSettings(object):
multiple_select = self.multiple_form.fields['featured_artists']
assert multiple_select.required is False
assert multiple_select.widget.allow_multiple_selected
output = multiple_select.widget.render('featured_artists', None)
assert '<option value=""></option>' not in output
assert 'data-placeholder=""' in output
def test_i18n(self):
translation.activate('de')
assert tuple(Select2Widget().media._js) == (
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/select2.min.js',
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/i18n/de.js',
'django_select2/django_select2.js'
)
translation.activate('en')
assert tuple(Select2Widget().media._js) == (
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/select2.min.js',
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/i18n/en.js',
'django_select2/django_select2.js'
)
translation.activate('00')
assert tuple(Select2Widget().media._js) == (
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/select2.min.js',
'django_select2/django_select2.js'
)
translation.activate('sr-cyrl')
assert tuple(Select2Widget().media._js) == (
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/select2.min.js',
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/i18n/sr-Cyrl.js',
'django_select2/django_select2.js'
)
pytest.importorskip("django", minversion="2.0.4")
translation.activate('zh-hans')
assert tuple(Select2Widget().media._js) == (
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/select2.min.js',
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/i18n/zh-CN.js',
'django_select2/django_select2.js'
)
translation.activate('zh-hant')
assert tuple(Select2Widget().media._js) == (
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/select2.min.js',
f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/i18n/zh-TW.js',
'django_select2/django_select2.js'
)
class TestSelect2MixinSettings:
def test_default_media(self):
sut = Select2Widget()
result = sut.media.render()
assert '//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js' in result
assert '//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css' in result
assert f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/js/select2.min.js' in result
assert f'//cdnjs.cloudflare.com/ajax/libs/select2/{settings.SELECT2_LIB_VERSION}/css/select2.min.css' in result
assert 'django_select2/django_select2.js' in result
def test_js_setting(self, settings):
@ -98,12 +159,24 @@ class TestSelect2MixinSettings(object):
assert 'alternate.js' in result
assert 'django_select2/django_select2.js' in result
def test_empty_js_setting(self, settings):
settings.SELECT2_JS = ''
sut = Select2Widget()
result = sut.media.render()
assert 'django_select2/django_select2.js' in result
def test_css_setting(self, settings):
settings.SELECT2_CSS = 'alternate.css'
sut = Select2Widget()
result = sut.media.render()
assert 'alternate.css' in result
def test_empty_css_setting(self, settings):
settings.SELECT2_CSS = ''
sut = Select2Widget()
result = sut.media.render()
assert '.css' not in result
class TestHeavySelect2Mixin(TestSelect2Mixin):
url = reverse('heavy_select2_widget')
@ -123,7 +196,9 @@ 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), \
not_required_field.widget.render('primary_genre', 1) or \
'<option value="1" selected>One</option>' in \
not_required_field.widget.render('primary_genre', 1), \
not_required_field.widget.render('primary_genre', 1)
def test_many_selected_option(self, db, genres):
@ -131,10 +206,12 @@ class TestHeavySelect2Mixin(TestSelect2Mixin):
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_option_a = '<option value="{pk}" selected>{value}</option>'.format(pk=1, value='One')
selected_option2 = '<option value="{pk}" selected="selected">{value}</option>'.format(pk=2, value='Two')
selected_option2a = '<option value="{pk}" selected>{value}</option>'.format(pk=2, value='Two')
assert selected_option in widget_output, widget_output
assert selected_option2 in widget_output
assert selected_option in widget_output or selected_option_a in widget_output, widget_output
assert selected_option2 in widget_output or selected_option2a in widget_output
def test_multiple_widgets(self, db, live_server, driver):
driver.get(live_server + self.url)
@ -142,10 +219,20 @@ class TestHeavySelect2Mixin(TestSelect2Mixin):
driver.find_element_by_css_selector('.select2-results')
elem1, elem2 = driver.find_elements_by_css_selector('.select2-selection')
elem1.click()
result1 = driver.find_element_by_css_selector('.select2-results li:first-child').text
search1 = driver.find_element_by_css_selector('.select2-search__field')
search1.send_keys('fo')
result1 = WebDriverWait(driver, 60).until(
expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.select2-results li:first-child'))
).text
elem2.click()
result2 = driver.find_element_by_css_selector('.select2-results li:first-child').text
search2 = driver.find_element_by_css_selector('.select2-search__field')
search2.send_keys('fo')
result2 = WebDriverWait(driver, 60).until(
expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.select2-results li:first-child'))
).text
assert result1 != result2
@ -155,12 +242,12 @@ class TestHeavySelect2Mixin(TestSelect2Mixin):
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)
assert isinstance(widget.get_url(), str)
def test_can_not_pickle(self):
widget = self.widget_cls(data_view='heavy_data_1', attrs={'class': 'my-class'})
class NoPickle(object):
class NoPickle:
pass
widget.no_pickle = NoPickle()
@ -170,11 +257,12 @@ class TestHeavySelect2Mixin(TestSelect2Mixin):
class TestModelSelect2Mixin(TestHeavySelect2Mixin):
form = forms.AlbumModelSelect2WidgetForm(initial={'primary_genre': 1})
multiple_form = forms.ArtistModelSelect2MultipleWidgetForm()
def test_initial_data(self, genres):
genre = genres[0]
form = self.form.__class__(initial={'primary_genre': genre.pk})
assert text_type(genre) in form.as_p()
assert str(genre) in form.as_p()
def test_label_from_instance_initial(self, genres):
genre = genres[0]
@ -182,7 +270,7 @@ class TestModelSelect2Mixin(TestHeavySelect2Mixin):
genre.save()
form = self.form.__class__(initial={'primary_genre': genre.pk})
assert genre.title not in form.as_p()
assert genre.title not in form.as_p(), form.as_p()
assert genre.title.upper() in form.as_p()
@pytest.fixture(autouse=True)
@ -198,10 +286,12 @@ class TestModelSelect2Mixin(TestHeavySelect2Mixin):
'primary_genre', genre.pk)
selected_option = '<option value="{pk}" selected="selected">{value}</option>'.format(
pk=genre.pk, value=force_text(genre))
selected_option_a = '<option value="{pk}" selected>{value}</option>'.format(
pk=genre.pk, value=force_text(genre))
unselected_option = '<option value="{pk}">{value}</option>'.format(
pk=genre2.pk, value=force_text(genre2))
assert selected_option in widget_output, widget_output
assert selected_option in widget_output or selected_option_a in widget_output, widget_output
assert unselected_option not in widget_output
def test_selected_option_label_from_instance(self, db, genres):
@ -212,14 +302,15 @@ class TestModelSelect2Mixin(TestHeavySelect2Mixin):
field = self.form.fields['primary_genre']
widget_output = field.widget.render('primary_genre', genre.pk)
def get_selected_option(genre):
def get_selected_options(genre):
return '<option value="{pk}" selected="selected">{value}</option>'.format(
pk=genre.pk, value=force_text(genre)), '<option value="{pk}" selected>{value}</option>'.format(
pk=genre.pk, value=force_text(genre))
assert get_selected_option(genre) not in widget_output
assert all(o not in widget_output for o in get_selected_options(genre))
genre.title = genre.title.upper()
assert get_selected_option(genre) in widget_output
assert any(o in widget_output for o in get_selected_options(genre))
def test_get_queryset(self):
widget = ModelSelect2Widget()
@ -231,40 +322,71 @@ class TestModelSelect2Mixin(TestHeavySelect2Mixin):
widget.queryset = Genre.objects.all()
assert isinstance(widget.get_queryset(), QuerySet)
def test_tag_attrs_Select2Widget(self):
widget = Select2Widget()
output = widget.render('name', 'value')
assert 'data-minimum-input-length="0"' in output
def test_custom_tag_attrs_Select2Widget(self):
widget = Select2Widget(attrs={'data-minimum-input-length': '3'})
output = widget.render('name', 'value')
assert 'data-minimum-input-length="3"' in output
def test_tag_attrs_ModelSelect2Widget(self):
widget = ModelSelect2Widget(queryset=Genre.objects.all(), search_fields=['title__icontains'])
output = widget.render('name', 'value')
assert 'data-minimum-input-length="2"' in output
def test_tag_attrs_ModelSelect2TagWidget(self):
widget = ModelSelect2TagWidget(queryset=Genre.objects.all(), search_fields=['title__icontains'])
output = widget.render('name', 'value')
assert 'data-minimum-input-length="2"' in output
def test_tag_attrs_HeavySelect2Widget(self):
widget = HeavySelect2Widget(data_url='/foo/bar/')
output = widget.render('name', 'value')
assert 'data-minimum-input-length="2"' in output
def test_custom_tag_attrs_ModelSelect2Widget(self):
widget = ModelSelect2Widget(
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
def test_get_search_fields(self):
widget = ModelSelect2Widget()
with pytest.raises(NotImplementedError):
widget.get_search_fields()
widget.search_fields = ['title__icontains']
assert isinstance(widget.get_search_fields(), collections.Iterable)
assert all(isinstance(x, text_type) for x in widget.get_search_fields())
assert isinstance(widget.get_search_fields(), Iterable)
assert all(isinstance(x, str) for x in widget.get_search_fields())
def test_filter_queryset(self, genres):
widget = TitleModelSelect2Widget(queryset=Genre.objects.all())
assert widget.filter_queryset(genres[0].title[:3]).exists()
assert widget.filter_queryset(None, genres[0].title[:3]).exists()
widget = TitleModelSelect2Widget(search_fields=['title__icontains'],
queryset=Genre.objects.all())
qs = widget.filter_queryset(" ".join([genres[0].title[:3], genres[0].title[3:]]))
qs = widget.filter_queryset(None, " ".join([genres[0].title[:3], genres[0].title[3:]]))
assert qs.exists()
def test_model_kwarg(self):
widget = ModelSelect2Widget(model=Genre, search_fields=['title__icontains'])
genre = Genre.objects.last()
result = widget.filter_queryset(genre.title)
result = widget.filter_queryset(None, genre.title)
assert result.exists()
def test_queryset_kwarg(self):
widget = ModelSelect2Widget(queryset=Genre.objects.all(), search_fields=['title__icontains'])
genre = Genre.objects.last()
result = widget.filter_queryset(genre.title)
result = widget.filter_queryset(None, genre.title)
assert result.exists()
def test_ajax_view_registration(self, client):
widget = ModelSelect2Widget(queryset=Genre.objects.all(), search_fields=['title__icontains'])
widget.render('name', 'value')
url = reverse('django_select2-json')
url = reverse('django_select2:auto-json')
genre = Genre.objects.last()
response = client.get(url, data=dict(field_id=signing.dumps(id(widget)), term=genre.title))
assert response.status_code == 200, response.content
@ -277,14 +399,28 @@ class TestModelSelect2Mixin(TestHeavySelect2Mixin):
widget.render('name', 'value')
cached_widget = cache.get(widget._get_cache_key())
assert cached_widget['max_results'] == widget.max_results
assert cached_widget['search_fields'] == widget.search_fields
assert cached_widget['search_fields'] == tuple(widget.search_fields)
qs = widget.get_queryset()
assert isinstance(cached_widget['queryset'][0], qs.__class__)
assert text_type(cached_widget['queryset'][1]) == text_type(qs.query)
assert str(cached_widget['queryset'][1]) == str(qs.query)
def test_get_url(self):
widget = ModelSelect2Widget(queryset=Genre.objects.all(), search_fields=['title__icontains'])
assert isinstance(widget.get_url(), text_type)
assert isinstance(widget.get_url(), str)
def test_custom_to_field_name(self):
the_best_band_in_the_world = Artist.objects.create(title='Take That')
groupie = Groupie.objects.create(obsession=the_best_band_in_the_world)
form = forms.GroupieForm(instance=groupie)
assert '<option value="Take That" selected>TAKE THAT</option>' in form.as_p()
def test_empty_label(self, db):
# Empty options is only required for single selects
# https://select2.github.io/options.html#allowClear
single_select = self.form.fields['primary_genre']
single_select.empty_label = 'Hello World'
assert single_select.required is False
assert 'data-placeholder="Hello World"' in single_select.widget.render('primary_genre', None)
class TestHeavySelect2TagWidget(TestHeavySelect2Mixin):
@ -292,7 +428,7 @@ class TestHeavySelect2TagWidget(TestHeavySelect2Mixin):
def test_tag_attrs(self):
widget = ModelSelect2TagWidget(queryset=Genre.objects.all(), search_fields=['title__icontains'])
output = widget.render('name', 'value')
assert 'data-minimum-input-length="1"' in output
assert 'data-minimum-input-length="2"' in output
assert 'data-tags="true"' in output
assert 'data-token-separators' in output
@ -303,13 +439,18 @@ class TestHeavySelect2TagWidget(TestHeavySelect2Mixin):
assert 'data-minimum-input-length="3"' in output
class TestHeavySelect2MultipleWidget(object):
class TestHeavySelect2MultipleWidget:
url = reverse('heavy_select2_multiple_widget')
form = forms.HeavySelect2MultipleWidgetForm()
widget_cls = HeavySelect2MultipleWidget
@pytest.mark.xfail(bool(os.environ.get('CI', False)),
reason='https://bugs.chromium.org/p/chromedriver/issues/detail?id=1772')
def test_widgets_selected_after_validation_error(self, db, live_server, driver):
driver.get(live_server + self.url)
WebDriverWait(driver, 3).until(
expected_conditions.presence_of_element_located((By.ID, 'id_title'))
)
title = driver.find_element_by_id('id_title')
title.send_keys('fo')
genres, fartists = driver.find_elements_by_css_selector('.select2-selection--multiple')
@ -319,8 +460,72 @@ class TestHeavySelect2MultipleWidget(object):
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
errstring = WebDriverWait(driver, 3).until(
expected_conditions.presence_of_element_located((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'
class TestAddressChainedSelect2Widget:
url = reverse('model_chained_select2_widget')
form = forms.AddressChainedSelect2WidgetForm()
def test_widgets_selected_after_validation_error(self, db, live_server, driver, countries, cities):
driver.get(live_server + self.url)
WebDriverWait(driver, 60).until(
expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.select2-selection--single'))
)
country_container, city_container = driver.find_elements_by_css_selector('.select2-selection--single')
# clicking city select2 lists all available cities
city_container.click()
WebDriverWait(driver, 60).until(
expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.select2-results li'))
)
city_options = driver.find_elements_by_css_selector('.select2-results li')
city_names_from_browser = {option.text for option in city_options}
city_names_from_db = set(City.objects.values_list('name', flat=True))
assert len(city_names_from_browser) == City.objects.count()
assert city_names_from_browser == city_names_from_db
# selecting a country really does it
country_container.click()
WebDriverWait(driver, 60).until(
expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.select2-results li:nth-child(2)'))
)
country_option = driver.find_element_by_css_selector('.select2-results li:nth-child(2)')
country_name = country_option.text
country_option.click()
assert country_name == country_container.text
# clicking city select2 lists reduced list of cities belonging to the country
city_container.click()
WebDriverWait(driver, 60).until(
expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.select2-results li'))
)
city_options = driver.find_elements_by_css_selector('.select2-results li')
city_names_from_browser = {option.text for option in city_options}
city_names_from_db = set(Country.objects.get(name=country_name).cities.values_list('name', flat=True))
assert len(city_names_from_browser) != City.objects.count()
assert city_names_from_browser == city_names_from_db
# selecting a city reaaly does it
city_option = driver.find_element_by_css_selector('.select2-results li:nth-child(2)')
city_name = city_option.text
city_option.click()
assert city_name == city_container.text
# clicking country select2 lists reduced list to the only country available to the city
country_container.click()
WebDriverWait(driver, 60).until(
expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.select2-results li'))
)
country_options = driver.find_elements_by_css_selector('.select2-results li')
country_names_from_browser = {option.text for option in country_options}
country_names_from_db = {City.objects.get(name=city_name).country.name}
assert len(country_names_from_browser) != Country.objects.count()
assert country_names_from_browser == country_names_from_db

View file

@ -1,10 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
from django.core import signing
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_text
from django_select2.cache import cache
@ -14,14 +10,19 @@ from tests.testapp.forms import (
)
from tests.testapp.models import Genre
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
class TestAutoResponseView(object):
class TestAutoResponseView:
def test_get(self, client, artists):
artist = artists[0]
form = AlbumModelSelect2WidgetForm()
assert form.as_p()
field_id = signing.dumps(id(form.fields['artist'].widget))
url = reverse('django_select2-json')
url = reverse('django_select2:auto-json')
response = client.get(url, {'field_id': field_id, 'term': artist.title})
assert response.status_code == 200
data = json.loads(response.content.decode('utf-8'))
@ -30,25 +31,25 @@ class TestAutoResponseView(object):
def test_no_field_id(self, client, artists):
artist = artists[0]
url = reverse('django_select2-json')
url = reverse('django_select2:auto-json')
response = client.get(url, {'term': artist.title})
assert response.status_code == 404
def test_wrong_field_id(self, client, artists):
artist = artists[0]
url = reverse('django_select2-json')
url = reverse('django_select2:auto-json')
response = client.get(url, {'field_id': 123, 'term': artist.title})
assert response.status_code == 404
def test_field_id_not_found(self, client, artists):
artist = artists[0]
field_id = signing.dumps(123456789)
url = reverse('django_select2-json')
url = reverse('django_select2:auto-json')
response = client.get(url, {'field_id': field_id, 'term': artist.title})
assert response.status_code == 404
def test_pagination(self, genres, client):
url = reverse('django_select2-json')
url = reverse('django_select2:auto-json')
widget = ModelSelect2Widget(
max_results=10,
model=Genre,
@ -71,7 +72,7 @@ class TestAutoResponseView(object):
assert data['more'] is False
def test_label_from_instance(self, artists, client):
url = reverse('django_select2-json')
url = reverse('django_select2:auto-json')
form = AlbumModelSelect2WidgetForm()
form.fields['artist'].widget = ArtistCustomTitleWidget()
@ -95,6 +96,6 @@ class TestAutoResponseView(object):
widget_dict = cache.get(cache_key)
widget_dict['url'] = 'yet/another/url'
cache.set(cache_key, widget_dict)
url = reverse('django_select2-json')
url = reverse('django_select2:auto-json')
response = client.get(url, {'field_id': field_id, 'term': artist.title})
assert response.status_code == 404

View file

@ -1,6 +1,3 @@
# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django import forms
from django.utils.encoding import force_text
@ -10,10 +7,10 @@ from django_select2.forms import (
Select2Widget
)
from tests.testapp import models
from tests.testapp.models import Album
from tests.testapp.models import Album, City, Country
class TitleSearchFieldMixin(object):
class TitleSearchFieldMixin:
search_fields = [
'title__icontains',
'pk__startswith'
@ -117,7 +114,13 @@ 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'),
@ -146,11 +149,19 @@ 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,
attrs={'data-minimum-input-length': 0},
),
choices=NUMBER_CHOICES
)
featured_artists = forms.MultipleChoiceField(
widget=HeavySelect2MultipleWidget(data_view='heavy_data_2', choices=NUMBER_CHOICES),
widget=HeavySelect2MultipleWidget(
data_view='heavy_data_2',
choices=NUMBER_CHOICES,
attrs={'data-minimum-input-length': 0},
),
choices=NUMBER_CHOICES,
required=False
)
@ -168,3 +179,36 @@ class ModelSelect2TagWidgetForm(forms.ModelForm):
widgets = {
'genres': GenreSelect2TagWidget
}
class AddressChainedSelect2WidgetForm(forms.Form):
country = forms.ModelChoiceField(
queryset=Country.objects.all(),
label='Country',
widget=ModelSelect2Widget(
search_fields=['name__icontains'],
max_results=500,
dependent_fields={'city': 'cities'},
attrs={'data-minimum-input-length': 0},
)
)
city = forms.ModelChoiceField(
queryset=City.objects.all(),
label='City',
widget=ModelSelect2Widget(
search_fields=['name__icontains'],
dependent_fields={'country': 'country'},
max_results=500,
attrs={'data-minimum-input-length': 0},
)
)
class GroupieForm(forms.ModelForm):
class Meta:
model = models.Groupie
fields = '__all__'
widgets = {
'obsession': ArtistCustomTitleWidget
}

View file

@ -1,34 +1,62 @@
# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Genre(models.Model):
title = models.CharField(max_length=50)
class Meta:
ordering = ('title',)
def __str__(self):
return self.title
@python_2_unicode_compatible
class Artist(models.Model):
title = models.CharField(max_length=50)
title = models.CharField(max_length=50, unique=True)
genres = models.ManyToManyField(Genre)
class Meta:
ordering = ('title',)
def __str__(self):
return self.title
@python_2_unicode_compatible
class Album(models.Model):
title = models.CharField(max_length=255)
artist = models.ForeignKey(Artist)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
featured_artists = models.ManyToManyField(Artist, blank=True, related_name='featured_album_set')
primary_genre = models.ForeignKey(Genre, blank=True, null=True, related_name='primary_album_set')
primary_genre = models.ForeignKey(Genre, on_delete=models.CASCADE, blank=True, null=True,
related_name='primary_album_set')
genres = models.ManyToManyField(Genre)
class Meta:
ordering = ('title',)
def __str__(self):
return self.title
class Country(models.Model):
name = models.CharField(max_length=255)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class City(models.Model):
name = models.CharField(max_length=255)
country = models.ForeignKey('Country', related_name="cities", on_delete=models.CASCADE)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class Groupie(models.Model):
obsession = models.ForeignKey(Artist, to_field='title', on_delete=models.CASCADE)

View file

@ -20,12 +20,6 @@ INSTALLED_APPS = (
'tests.testapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
@ -33,21 +27,20 @@ MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
SITE_ID = 1
ROOT_URLCONF = 'tests.testapp.urls'
LANGUAGES = [
('de', 'German'),
('en', 'English'),
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': ['templates'],
},
]
SECRET_KEY = '123456'
USE_L10N = True
if os.environ.get('TRAVIS'):
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': 'localhost:11211',
}
}
USE_I18N = True

View file

@ -1,4 +1,4 @@
{% load staticfiles %}
{% load static %}
<!DOCTYPE html>
<html>
<head>
@ -15,11 +15,11 @@
{{ form }}
<input type="submit" value="Submit Form"/>
</form>
<script src="{% static '//code.jquery.com/jquery-2.1.4.min.js' %}"></script>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
window.onerror = function (msg) {
$("body").attr("JSError", msg);
}
</script>
{{ form.media.js }}
</body>
</body>

View file

@ -1,33 +1,35 @@
# -*- conding:utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import include, url
from django.urls import include, path
from .forms import (
AlbumModelSelect2WidgetForm, HeavySelect2MultipleWidgetForm,
HeavySelect2WidgetForm, ModelSelect2TagWidgetForm, Select2WidgetForm
AddressChainedSelect2WidgetForm, AlbumModelSelect2WidgetForm,
HeavySelect2MultipleWidgetForm, HeavySelect2WidgetForm,
ModelSelect2TagWidgetForm, Select2WidgetForm
)
from .views import TemplateFormView, heavy_data_1, heavy_data_2
urlpatterns = [
url(r'^select2_widget/$',
TemplateFormView.as_view(form_class=Select2WidgetForm), name='select2_widget'),
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, success_url='/'),
name='heavy_select2_multiple_widget'),
path('select2_widget',
TemplateFormView.as_view(form_class=Select2WidgetForm), name='select2_widget'),
path('heavy_select2_widget',
TemplateFormView.as_view(form_class=HeavySelect2WidgetForm), name='heavy_select2_widget'),
path('heavy_select2_multiple_widget',
TemplateFormView.as_view(form_class=HeavySelect2MultipleWidgetForm, success_url='/'),
name='heavy_select2_multiple_widget'),
url(r'^model_select2_widget/$',
TemplateFormView.as_view(form_class=AlbumModelSelect2WidgetForm),
name='model_select2_widget'),
path('model_select2_widget',
TemplateFormView.as_view(form_class=AlbumModelSelect2WidgetForm),
name='model_select2_widget'),
url(r'^model_select2_tag_widget/$',
TemplateFormView.as_view(form_class=ModelSelect2TagWidgetForm),
name='model_select2_tag_widget'),
path('model_select2_tag_widget',
TemplateFormView.as_view(form_class=ModelSelect2TagWidgetForm),
name='model_select2_tag_widget'),
url(r'^heavy_data_1/$', heavy_data_1, name='heavy_data_1'),
url(r'^heavy_data_2/$', heavy_data_2, name='heavy_data_2'),
path('model_chained_select2_widget',
TemplateFormView.as_view(form_class=AddressChainedSelect2WidgetForm),
name='model_chained_select2_widget'),
url(r'^select2/', include('django_select2.urls')),
path('heavy_data_1', heavy_data_1, name='heavy_data_1'),
path('heavy_data_2', heavy_data_2, name='heavy_data_2'),
path('select2/', include('django_select2.urls')),
]

View file

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.http import HttpResponse