mirror of
https://github.com/Hopiu/django-select2.git
synced 2026-05-21 11:11:52 +00:00
Compare commits
256 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7fa49a6e2 | ||
|
|
39ab326884 | ||
|
|
d63f410bca | ||
|
|
5680f0daf9 | ||
|
|
8deb2b6a11 | ||
|
|
37e2515be6 | ||
|
|
cc8989a625 | ||
|
|
1ae52d7436 | ||
|
|
dca7dbc5d1 | ||
|
|
8bd7f7209f | ||
|
|
6b1ca10b06 | ||
|
|
4f96e21333 | ||
|
|
8494b10fcc | ||
|
|
ff68bf1050 | ||
|
|
c15de464d5 | ||
|
|
898b2e84dd | ||
|
|
1e4056bd62 | ||
|
|
2bb6f3a974 | ||
|
|
fa9d8baba8 | ||
|
|
df5bf9e893 | ||
|
|
4d0d702aaf | ||
|
|
0c82edf65c | ||
|
|
0021f35b2a | ||
|
|
ad42a01083 | ||
|
|
3a7ecd1666 | ||
|
|
2f17e21b0b | ||
|
|
9de7f29815 | ||
|
|
ffe91627d8 | ||
|
|
66d2051c20 | ||
|
|
48ceeaa312 | ||
|
|
9b54cc30c7 | ||
|
|
82859121a6 | ||
|
|
d34cd2e5de | ||
|
|
e4efaab6f1 | ||
|
|
1e8971c12b | ||
|
|
de7e7a1903 | ||
|
|
0f18958099 | ||
|
|
ebbdd2b9be | ||
|
|
e9d96cf856 | ||
|
|
f6eaa26c16 | ||
|
|
73d4be8992 | ||
|
|
e1d42bfcad | ||
|
|
1954bf57fa | ||
|
|
08ca1c1c36 | ||
|
|
aef27f48df | ||
|
|
f31beec0c4 | ||
|
|
496cc7c502 | ||
|
|
17af750d88 | ||
|
|
67bf060991 | ||
|
|
d9c899e8f7 | ||
|
|
e4729feb9a | ||
|
|
2ea6ef8edb | ||
|
|
a9aa31146f | ||
|
|
c2331b272a | ||
|
|
5d98048c9f | ||
|
|
7782e9bc3d | ||
|
|
426cace3a3 | ||
|
|
90fbf7422f | ||
|
|
f6d5afe51d | ||
|
|
19e2e50921 | ||
|
|
937dcac08b | ||
|
|
322b389ad3 | ||
|
|
ac7050d2db | ||
|
|
d4dcc5f3c0 | ||
|
|
cca6583d48 | ||
|
|
1b1f345b3d | ||
|
|
e09951ce62 | ||
|
|
f967eb643b | ||
|
|
176be2fdcf | ||
|
|
e1f5b7d999 | ||
|
|
5f263f9385 | ||
|
|
3ebad0dc12 | ||
|
|
00c082bd6d | ||
|
|
3cc666e46d | ||
|
|
47c191fe13 | ||
|
|
4ebbb05d11 | ||
|
|
4ba7ecb8a0 | ||
|
|
2b2b11fdf4 | ||
|
|
88319ecc47 | ||
|
|
4c0139f253 | ||
|
|
fdfdbbb512 | ||
|
|
15201d1c7e | ||
|
|
da6867c083 | ||
|
|
6153f4778a | ||
|
|
58d8a9faa8 | ||
|
|
1a27c3562d | ||
|
|
b81b7f4d0c | ||
|
|
c07194e382 | ||
|
|
c4b3fdfbef | ||
|
|
2000395c3b | ||
|
|
8911ad91b2 | ||
|
|
5dec946658 | ||
|
|
85ffeda276 | ||
|
|
44d0039d49 | ||
|
|
a3f4a28ff1 | ||
|
|
403a32ff46 | ||
|
|
cca167bd24 | ||
|
|
90028d9e36 | ||
|
|
ec3462e87a | ||
|
|
db5ec06f83 | ||
|
|
b46f69f166 | ||
|
|
b88e26bfa2 | ||
|
|
78c54f2c47 | ||
|
|
018701680b | ||
|
|
d4668e3125 | ||
|
|
bc0eab96e0 | ||
|
|
6d2bd1cbd3 | ||
|
|
9d215f6efe | ||
|
|
5741279d0e | ||
|
|
12b0d472b8 | ||
|
|
74d2266817 | ||
|
|
c46fd5a5ec | ||
|
|
ad938c6008 | ||
|
|
2c1ae2df92 | ||
|
|
6260226ae5 | ||
|
|
a5bb222ea8 | ||
|
|
f12e624cb8 | ||
|
|
c0d6fcb663 | ||
|
|
6dc2f3eb19 | ||
|
|
26f2a36dc6 | ||
|
|
d6180e05fc | ||
|
|
67b7e755fe | ||
|
|
4147cac2f8 | ||
|
|
55e481470e | ||
|
|
7297ed7fde | ||
|
|
90be63441b | ||
|
|
d6e056c009 | ||
|
|
a910581f7a | ||
|
|
1931a98240 | ||
|
|
5840622794 | ||
|
|
dc6e87e7ba | ||
|
|
71a836c892 | ||
|
|
735d5931d6 | ||
|
|
9cc0a9d62d | ||
|
|
dfdc626ad3 | ||
|
|
07e8029026 | ||
|
|
1f9d564445 | ||
|
|
5099b8d44d | ||
|
|
8958940c43 | ||
|
|
d6202c4108 | ||
|
|
0d560c08fc | ||
|
|
17dff07690 | ||
|
|
c6d7054e16 | ||
|
|
a89fedbe75 | ||
|
|
0918cae3e7 | ||
|
|
8f6e33845e | ||
|
|
46a50f377b | ||
|
|
895a7e519a | ||
|
|
c235c2e3f0 | ||
|
|
9a658b3b0f | ||
|
|
efb120b47d | ||
|
|
b34642dcef | ||
|
|
8b64b5d4fa | ||
|
|
4e8b2c24a3 | ||
|
|
23e91c8bb0 | ||
|
|
e88c0e059c | ||
|
|
047ee28722 | ||
|
|
6018b60fea | ||
|
|
f1e0752f2d | ||
|
|
172ef79ffd | ||
|
|
36a9ab7bab | ||
|
|
09110a5460 | ||
|
|
ec1c81ad87 | ||
|
|
3673e55195 | ||
|
|
937874127f | ||
|
|
681ced9f15 | ||
|
|
e375a58b4d | ||
|
|
b2609256f5 | ||
|
|
b676e563e2 | ||
|
|
65cfc12be3 | ||
|
|
e6ace9a8bc | ||
|
|
c3a48de1a3 | ||
|
|
8a463752a0 | ||
|
|
c364394450 | ||
|
|
977f2c3e25 | ||
|
|
aa15810d92 | ||
|
|
4a5c13a35f | ||
|
|
584e2e9f89 | ||
|
|
33a7e03acf | ||
|
|
93dab02fd1 | ||
|
|
d364dc9630 | ||
|
|
701d57ef31 | ||
|
|
71c6e1d9c3 | ||
|
|
7c2a898cfa | ||
|
|
6180846345 | ||
|
|
9430a950c2 | ||
|
|
1f9b094b67 | ||
|
|
15dbbf41a7 | ||
|
|
fb3bc19595 | ||
|
|
f03d7d44a8 | ||
|
|
e3c6919bbd | ||
|
|
9f5644b479 | ||
|
|
c797e59584 | ||
|
|
72616f8276 | ||
|
|
99aed19308 | ||
|
|
74bf15ce48 | ||
|
|
57dfd53d55 | ||
|
|
f943fe07f5 | ||
|
|
a6a12d7392 | ||
|
|
f579f4af35 | ||
|
|
0b3abb8f1f | ||
|
|
01c8979100 | ||
|
|
f6ee1f57db | ||
|
|
894a251be3 | ||
|
|
9ed8f58fa6 | ||
|
|
a8a4baf04d | ||
|
|
5b0400dfaa | ||
|
|
7923eeb0ee | ||
|
|
f09f9e5249 | ||
|
|
031ec6682c | ||
|
|
4dacbdf283 | ||
|
|
bc9601b3d3 | ||
|
|
d57b726d34 | ||
|
|
d25e733c85 | ||
|
|
27091f5b49 | ||
|
|
8d48887f5c | ||
|
|
fa6a841746 | ||
|
|
0ee50d9866 | ||
|
|
7d8908daab | ||
|
|
4a1b83ad1e | ||
|
|
33a00c1e39 | ||
|
|
89674ec375 | ||
|
|
e655ed7a59 | ||
|
|
3c06873148 | ||
|
|
84e1abaf4e | ||
|
|
6ebeb4c6d7 | ||
|
|
7d8a7e7a9f | ||
|
|
9ba75bb820 | ||
|
|
cfc7c2c541 | ||
|
|
6c5e2036ca | ||
|
|
4defb8112b | ||
|
|
bb90be77b7 | ||
|
|
18647161a1 | ||
|
|
3e6c1fc3ba | ||
|
|
19a8d63bb1 | ||
|
|
0457617738 | ||
|
|
974ba552b0 | ||
|
|
2beb5d23c7 | ||
|
|
b8d53aa714 | ||
|
|
b0d2325c43 | ||
|
|
9d1bcfee6a | ||
|
|
2c1eb8bc4a | ||
|
|
a91e66bf9e | ||
|
|
75c8c38e2d | ||
|
|
dc81c2b3b5 | ||
|
|
48ea7549a6 | ||
|
|
485ea191cb | ||
|
|
4d484163c2 | ||
|
|
85f76d7ba5 | ||
|
|
e184f5fea6 | ||
|
|
f301dc6f9d | ||
|
|
5dfd8553cc | ||
|
|
f80abb10f2 | ||
|
|
6dad55eb11 | ||
|
|
95297a362e | ||
|
|
33b7dffca1 |
112 changed files with 2749 additions and 915628 deletions
2
.bandit
Normal file
2
.bandit
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
[bandit]
|
||||||
|
exclude: tests
|
||||||
20
.editorconfig
Normal file
20
.editorconfig
Normal 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
4
.fussyfox.yml
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
- bandit
|
||||||
|
- flake8
|
||||||
|
- isort
|
||||||
|
- pydocstyle
|
||||||
2
.github/FUNDING.yml
vendored
Normal file
2
.github/FUNDING.yml
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
github: codingjoe
|
||||||
|
custom: https://paypal.me/codingjoe
|
||||||
30
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
30
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal 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.
|
||||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal 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.
|
||||||
13
.github/ISSUE_TEMPLATE/problem-with-django-admin.md
vendored
Normal file
13
.github/ISSUE_TEMPLATE/problem-with-django-admin.md
vendored
Normal 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
17
.github/ISSUE_TEMPLATE/question.md
vendored
Normal 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.
|
||||||
12
.gitignore
vendored
12
.gitignore
vendored
|
|
@ -1,6 +1,3 @@
|
||||||
|
|
||||||
testapp/tt.py
|
|
||||||
|
|
||||||
*.pyc
|
*.pyc
|
||||||
|
|
||||||
Django_Select2.egg-info
|
Django_Select2.egg-info
|
||||||
|
|
@ -8,6 +5,8 @@ Django_Select2_Py3.egg-info
|
||||||
dist
|
dist
|
||||||
build
|
build
|
||||||
|
|
||||||
|
node_modules/
|
||||||
|
|
||||||
docs/_build
|
docs/_build
|
||||||
|
|
||||||
# Intellij
|
# Intellij
|
||||||
|
|
@ -17,3 +16,10 @@ docs/_build
|
||||||
env/
|
env/
|
||||||
venv/
|
venv/
|
||||||
.cache/
|
.cache/
|
||||||
|
.tox/
|
||||||
|
geckodriver.log
|
||||||
|
ghostdriver.log
|
||||||
|
.coverage
|
||||||
|
|
||||||
|
coverage.xml
|
||||||
|
.eggs/
|
||||||
|
|
|
||||||
109
.travis.yml
109
.travis.yml
|
|
@ -1,34 +1,87 @@
|
||||||
language: python
|
language: python
|
||||||
sudo: false
|
dist: xenial
|
||||||
|
|
||||||
python:
|
python:
|
||||||
- "2.7"
|
- "3.6"
|
||||||
- "3.3"
|
- "3.7"
|
||||||
- "3.4"
|
- "3.8"
|
||||||
- "pypy"
|
|
||||||
- "pypy3"
|
|
||||||
env:
|
env:
|
||||||
global:
|
- DJANGO=22
|
||||||
- DISPLAY=:99.0
|
- DJANGO=30
|
||||||
matrix:
|
- DJANGO=master
|
||||||
- DJANGO="Django<1.7,>=1.6"
|
|
||||||
- DJANGO="Django<1.8,>=1.7"
|
|
||||||
- DJANGO="Django<1.9,>=1.8"
|
|
||||||
- DJANGO="-e git+https://github.com/django/django.git@master#egg=Django"
|
|
||||||
matrix:
|
matrix:
|
||||||
fast_finish: true
|
fast_finish: true
|
||||||
allow_failures:
|
allow_failures:
|
||||||
- env: DJANGO="<1.7,>=1.6"
|
- env: DJANGO=master
|
||||||
- env: DJANGO="-e git+https://github.com/django/django.git@master#egg=Django"
|
|
||||||
- python: "pypy"
|
addons:
|
||||||
- python: "pypy3"
|
apt:
|
||||||
install:
|
packages:
|
||||||
- pip install --upgrade pip
|
- chromium-chromedriver
|
||||||
- pip install -e .
|
|
||||||
- pip install -r requirements_dev.txt
|
install: pip install tox-travis codecov
|
||||||
- pip install $DJANGO
|
|
||||||
- pip install coveralls
|
before_script:
|
||||||
- sh -e /etc/init.d/xvfb start
|
- ln -s /usr/lib/chromium-browser/chromedriver ~/bin/chromedriver
|
||||||
script:
|
- |
|
||||||
- coverage run --source=django_select2 runtests.py
|
if [[ -z $TOXENV ]]; then
|
||||||
after_success:
|
export TOXENV=py$(echo $TRAVIS_PYTHON_VERSION | sed -e 's/\.//g')-dj$DJANGO
|
||||||
coveralls
|
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=
|
||||||
|
|
|
||||||
118
CHANGELOG.md
118
CHANGELOG.md
|
|
@ -1,118 +0,0 @@
|
||||||
Changelog Summary
|
|
||||||
=================
|
|
||||||
|
|
||||||
### 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
22
CONTRIBUTING.rst
Normal 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.
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
Creating bundle
|
|
||||||
===============
|
|
||||||
|
|
||||||
$ python setup.py sdist
|
|
||||||
|
|
||||||
Uploading bundle to PyPi
|
|
||||||
========================
|
|
||||||
|
|
||||||
$ python setup.py sdist upload
|
|
||||||
|
|
||||||
OR
|
|
||||||
|
|
||||||
|
|
||||||
$ python setup.py sdist upload -r pypi
|
|
||||||
|
|
||||||
This needs we have a ~/.pypi file. Its content should be like:-
|
|
||||||
|
|
||||||
[distutils] # this tells distutils what package indexes you can push to
|
|
||||||
index-servers =
|
|
||||||
pypi
|
|
||||||
pypitest #Optional
|
|
||||||
|
|
||||||
[pypi]
|
|
||||||
repository: https://pypi.python.org/pypi
|
|
||||||
username: <username>
|
|
||||||
password: <password>
|
|
||||||
|
|
||||||
[pypitest] #Optional
|
|
||||||
repository: https://testpypi.python.org/pypi
|
|
||||||
username: <username>
|
|
||||||
password: <password>
|
|
||||||
21
LICENSE
Normal file
21
LICENSE
Normal 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.
|
||||||
176
LICENSE.txt
176
LICENSE.txt
|
|
@ -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
|
|
||||||
12
MANIFEST.in
12
MANIFEST.in
|
|
@ -1,8 +1,6 @@
|
||||||
include *.txt *.md
|
include django_select2/static/django_select2/django_select2.js
|
||||||
recursive-include django_select2/static *.*
|
|
||||||
recursive-exclude django_select2/static .DS_Store
|
|
||||||
recursive-include django_select2/templatetags *.*
|
|
||||||
recursive-exclude django_select2/templatetags .DS_Store *.pyc
|
|
||||||
exclude UK_Advanced_Cryptics_Dictionary_Licensing_Information.txt
|
|
||||||
exclude Internal_Notes.md
|
|
||||||
prune tests
|
prune tests
|
||||||
|
prune .github
|
||||||
|
exclude .fussyfox.yml
|
||||||
|
exclude .travis.yml
|
||||||
|
exclude .gitignore
|
||||||
|
|
|
||||||
86
README
86
README
|
|
@ -1,86 +0,0 @@
|
||||||
Django-Select2
|
|
||||||
==============
|
|
||||||
|
|
||||||
[](https://pypi.python.org/pypi/Django-Select2/)
|
|
||||||
[](https://travis-ci.org/applegrew/django-select2)
|
|
||||||
[](https://landscape.io/github/applegrew/django-select2/master)
|
|
||||||
[](https://coveralls.io/r/applegrew/django-select2)
|
|
||||||
[](https://raw.githubusercontent.com/applegrew/django-select2/master/LICENSE.txt)
|
|
||||||
[](https://gitter.im/applegrew/django-select2?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
|
||||||
|
|
||||||
This is a [Django](https://www.djangoproject.com/) integration of [Select2](http://ivaynberg.github.com/select2/).
|
|
||||||
|
|
||||||
The app includes Select2 driven Django Widgets and Form Fields.
|
|
||||||
|
|
||||||
Installation
|
|
||||||
============
|
|
||||||
|
|
||||||
1. Install `django_select2`
|
|
||||||
|
|
||||||
pip install django_select2
|
|
||||||
|
|
||||||
2. Add `django_select2` to your `INSTALLED_APPS` in your project settings.
|
|
||||||
|
|
||||||
3. When deploying on production server, run :-
|
|
||||||
|
|
||||||
python manage.py collectstatic
|
|
||||||
|
|
||||||
4. Add `django_select` to your urlconf if you use any 'Auto' fields.
|
|
||||||
|
|
||||||
url(r'^select2/', include('django_select2.urls')),
|
|
||||||
|
|
||||||
|
|
||||||
Documentation
|
|
||||||
=============
|
|
||||||
|
|
||||||
Documentation available at http://django-select2.readthedocs.org/.
|
|
||||||
|
|
||||||
More details
|
|
||||||
============
|
|
||||||
|
|
||||||
More details can be found on my blog at - http://blog.applegrew.com/2012/08/django-select2/.
|
|
||||||
|
|
||||||
External Dependencies
|
|
||||||
=====================
|
|
||||||
|
|
||||||
* Django - This is obvious.
|
|
||||||
* jQuery - This is not included in the package since it is expected that in most scenarios this would already be available.
|
|
||||||
* Memcached (python-memcached) - If you plan on running multiple python processes with `GENERATE_RANDOM_SELECT2_ID` enabled, then you need to turn on `ENABLE_SELECT2_MULTI_PROCESS_SUPPORT`. In that mode it is highly recommended that you use Memcached, to minimize DB hits.
|
|
||||||
|
|
||||||
Example Application
|
|
||||||
===================
|
|
||||||
Please see `testapp` application. This application is used to manually test the functionalities of this package. This also serves as a good example.
|
|
||||||
|
|
||||||
You need only Django 1.4 or above to run that. It might run on older versions but that is not tested.
|
|
||||||
|
|
||||||
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.
|
|
||||||
86
README.md
86
README.md
|
|
@ -1,86 +0,0 @@
|
||||||
Django-Select2
|
|
||||||
==============
|
|
||||||
|
|
||||||
[](https://pypi.python.org/pypi/Django-Select2/)
|
|
||||||
[](https://travis-ci.org/applegrew/django-select2)
|
|
||||||
[](https://landscape.io/github/applegrew/django-select2/master)
|
|
||||||
[](https://coveralls.io/r/applegrew/django-select2)
|
|
||||||
[](https://raw.githubusercontent.com/applegrew/django-select2/master/LICENSE.txt)
|
|
||||||
[](https://gitter.im/applegrew/django-select2?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
|
||||||
|
|
||||||
This is a [Django](https://www.djangoproject.com/) integration of [Select2](http://ivaynberg.github.com/select2/).
|
|
||||||
|
|
||||||
The app includes Select2 driven Django Widgets and Form Fields.
|
|
||||||
|
|
||||||
Installation
|
|
||||||
============
|
|
||||||
|
|
||||||
1. Install `django_select2`
|
|
||||||
|
|
||||||
pip install django_select2
|
|
||||||
|
|
||||||
2. Add `django_select2` to your `INSTALLED_APPS` in your project settings.
|
|
||||||
|
|
||||||
3. When deploying on production server, run :-
|
|
||||||
|
|
||||||
python manage.py collectstatic
|
|
||||||
|
|
||||||
4. Add `django_select` to your urlconf if you use any 'Auto' fields.
|
|
||||||
|
|
||||||
url(r'^select2/', include('django_select2.urls')),
|
|
||||||
|
|
||||||
|
|
||||||
Documentation
|
|
||||||
=============
|
|
||||||
|
|
||||||
Documentation available at http://django-select2.readthedocs.org/.
|
|
||||||
|
|
||||||
More details
|
|
||||||
============
|
|
||||||
|
|
||||||
More details can be found on my blog at - http://blog.applegrew.com/2012/08/django-select2/.
|
|
||||||
|
|
||||||
External Dependencies
|
|
||||||
=====================
|
|
||||||
|
|
||||||
* Django - This is obvious.
|
|
||||||
* jQuery - This is not included in the package since it is expected that in most scenarios this would already be available.
|
|
||||||
* Memcached (python-memcached) - If you plan on running multiple python processes with `GENERATE_RANDOM_SELECT2_ID` enabled, then you need to turn on `ENABLE_SELECT2_MULTI_PROCESS_SUPPORT`. In that mode it is highly recommended that you use Memcached, to minimize DB hits.
|
|
||||||
|
|
||||||
Example Application
|
|
||||||
===================
|
|
||||||
Please see `testapp` application. This application is used to manually test the functionalities of this package. This also serves as a good example.
|
|
||||||
|
|
||||||
You need only Django 1.4 or above to run that. It might run on older versions but that is not tested.
|
|
||||||
|
|
||||||
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
69
README.rst
Normal 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
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
The following license applies to the wordlist (for model testmain.word) included in testapp/testmain/fixtures/initial_data.json.
|
|
||||||
|
|
||||||
Src: http://dreamsteep.com/projects/the-english-open-word-list.html
|
|
||||||
======================================================================================
|
|
||||||
|
|
||||||
UK Advanced Cryptics Dictionary Licensing Information:
|
|
||||||
|
|
||||||
Copyright © J Ross Beresford 1993-1999. All Rights Reserved.
|
|
||||||
|
|
||||||
The following restriction is placed on the use of this publication: if the UK Advanced Cryptics Dictionary is used in a software package or redistributed in any form, the copyright notice must be prominently displayed and the text of this document must be included verbatim.
|
|
||||||
|
|
||||||
There are no other restrictions: I would like to see the list distributed as widely as possible.
|
|
||||||
|
|
@ -1,135 +1,10 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
"""
|
"""
|
||||||
This is a Django_ integration of Select2_.
|
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/
|
.. _Django: https://www.djangoproject.com/
|
||||||
.. _Select2: http://ivaynberg.github.com/select2/
|
.. _Select2: http://ivaynberg.github.com/select2/
|
||||||
|
|
||||||
Widgets
|
|
||||||
-------
|
|
||||||
|
|
||||||
These components are responsible for rendering the necessary JavaScript and HTML markups. Since this whole
|
|
||||||
package is to render choices using Select2 JavaScript library, hence these components are meant to be used
|
|
||||||
with choice fields.
|
|
||||||
|
|
||||||
Widgets are generally of two types :-
|
|
||||||
|
|
||||||
1. **Light** --
|
|
||||||
They are not meant to be used when there are too many options, say, in thousands. This
|
|
||||||
is because all those options would have to be pre-rendered onto the page and JavaScript would
|
|
||||||
be used to search through them. Said that, they are also one the most easiest to use. They are almost
|
|
||||||
drop-in-replacement for Django's default select widgets.
|
|
||||||
|
|
||||||
2. **Heavy** --
|
|
||||||
They are suited for scenarios when the number of options are large and need complex queries
|
|
||||||
(from maybe different sources) to get the options. This dynamic fetching of options undoubtedly requires
|
|
||||||
Ajax communication with the server. Django-Select2 includes a helper JS file which is included automatically,
|
|
||||||
so you need not worry about writing any Ajax related JS code. Although on the server side you do need to
|
|
||||||
create a view specifically to respond to the queries.
|
|
||||||
|
|
||||||
Heavies have further specialized versions called -- **Auto Heavy**. 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.
|
|
||||||
|
|
||||||
**Available widgets:**
|
|
||||||
|
|
||||||
:py:class:`.Select2Widget`, :py:class:`.Select2MultipleWidget`, :py:class:`.HeavySelect2Widget`, :py:class:`.HeavySelect2MultipleWidget`,
|
|
||||||
:py:class:`.AutoHeavySelect2Widget`, :py:class:`.AutoHeavySelect2MultipleWidget`, :py:class:`.HeavySelect2TagWidget`,
|
|
||||||
:py:class:`.AutoHeavySelect2TagWidget`
|
|
||||||
|
|
||||||
`Read more`_
|
|
||||||
|
|
||||||
Fields
|
|
||||||
------
|
|
||||||
|
|
||||||
These are pre-implemented choice fields which use the above widgets. It is highly recommended that you use them
|
|
||||||
instead of rolling your own.
|
|
||||||
|
|
||||||
The fields available are good for general purpose use, although more specialized versions too are available for
|
|
||||||
your ease.
|
|
||||||
|
|
||||||
**Available fields:**
|
|
||||||
|
|
||||||
:py:class:`.Select2ChoiceField`, :py:class:`.Select2MultipleChoiceField`, :py:class:`.HeavySelect2ChoiceField`,
|
|
||||||
:py:class:`.HeavySelect2MultipleChoiceField`, :py:class:`.HeavyModelSelect2ChoiceField`,
|
|
||||||
:py:class:`.HeavyModelSelect2MultipleChoiceField`, :py:class:`.ModelSelect2Field`, :py:class:`.ModelSelect2MultipleField`,
|
|
||||||
:py:class:`.AutoSelect2Field`, :py:class:`.AutoSelect2MultipleField`, :py:class:`.AutoModelSelect2Field`,
|
|
||||||
:py:class:`.AutoModelSelect2MultipleField`, :py:class:`.HeavySelect2TagField`, :py:class:`.AutoSelect2TagField`,
|
|
||||||
:py:class:`.HeavyModelSelect2TagField`, :py:class:`.AutoModelSelect2TagField`
|
|
||||||
|
|
||||||
Views
|
|
||||||
-----
|
|
||||||
|
|
||||||
The view - `Select2View`, exposed here is meant to be used with 'Heavy' fields and widgets.
|
|
||||||
|
|
||||||
**Imported:**
|
|
||||||
|
|
||||||
:py:class:`.Select2View`, :py:data:`.NO_ERR_RESP`
|
|
||||||
|
|
||||||
`Read more`_
|
|
||||||
|
|
||||||
.. _Read more: http://blog.applegrew.com/2012/08/django-select2/
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from __future__ import absolute_import, unicode_literals
|
default_app_config = 'django_select2.apps.Select2AppConfig'
|
||||||
|
|
||||||
import logging
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
__version__ = "4.3.2"
|
|
||||||
|
|
||||||
__RENDER_SELECT2_STATICS = False
|
|
||||||
__ENABLE_MULTI_PROCESS_SUPPORT = False
|
|
||||||
__MEMCACHE_HOST = None
|
|
||||||
__MEMCACHE_PORT = None
|
|
||||||
__MEMCACHE_TTL = 900
|
|
||||||
__GENERATE_RANDOM_ID = False
|
|
||||||
__SECRET_SALT = ''
|
|
||||||
__BOOTSTRAP = False
|
|
||||||
|
|
||||||
try:
|
|
||||||
from django.conf import settings
|
|
||||||
if logger.isEnabledFor(logging.DEBUG):
|
|
||||||
logger.debug("Django found.")
|
|
||||||
if settings.configured:
|
|
||||||
__RENDER_SELECT2_STATICS = getattr(settings, 'AUTO_RENDER_SELECT2_STATICS', True)
|
|
||||||
__ENABLE_MULTI_PROCESS_SUPPORT = getattr(settings, 'ENABLE_SELECT2_MULTI_PROCESS_SUPPORT', False)
|
|
||||||
__MEMCACHE_HOST = getattr(settings, 'SELECT2_MEMCACHE_HOST', None)
|
|
||||||
__MEMCACHE_PORT = getattr(settings, 'SELECT2_MEMCACHE_PORT', None)
|
|
||||||
__MEMCACHE_TTL = getattr(settings, 'SELECT2_MEMCACHE_TTL', 900)
|
|
||||||
__GENERATE_RANDOM_ID = getattr(settings, 'GENERATE_RANDOM_SELECT2_ID', False)
|
|
||||||
__SECRET_SALT = getattr(settings, 'SECRET_KEY', '')
|
|
||||||
__BOOTSTRAP = getattr(settings, 'SELECT2_BOOTSTRAP', False)
|
|
||||||
|
|
||||||
if not __GENERATE_RANDOM_ID and __ENABLE_MULTI_PROCESS_SUPPORT:
|
|
||||||
logger.warn("You need not turn on ENABLE_SELECT2_MULTI_PROCESS_SUPPORT when GENERATE_RANDOM_SELECT2_ID is disabled.")
|
|
||||||
__ENABLE_MULTI_PROCESS_SUPPORT = False
|
|
||||||
|
|
||||||
from .widgets import (
|
|
||||||
Select2Widget, Select2MultipleWidget,
|
|
||||||
HeavySelect2Widget, HeavySelect2MultipleWidget,
|
|
||||||
AutoHeavySelect2Widget, AutoHeavySelect2MultipleWidget,
|
|
||||||
HeavySelect2TagWidget, AutoHeavySelect2TagWidget
|
|
||||||
) # NOQA
|
|
||||||
from .fields import (
|
|
||||||
Select2ChoiceField, Select2MultipleChoiceField,
|
|
||||||
HeavySelect2ChoiceField, HeavySelect2MultipleChoiceField,
|
|
||||||
HeavyModelSelect2ChoiceField, HeavyModelSelect2MultipleChoiceField,
|
|
||||||
ModelSelect2Field, ModelSelect2MultipleField,
|
|
||||||
AutoSelect2Field, AutoSelect2MultipleField,
|
|
||||||
AutoModelSelect2Field, AutoModelSelect2MultipleField,
|
|
||||||
HeavySelect2TagField, AutoSelect2TagField,
|
|
||||||
HeavyModelSelect2TagField, AutoModelSelect2TagField
|
|
||||||
) # NOQA
|
|
||||||
from .views import Select2View, NO_ERR_RESP
|
|
||||||
|
|
||||||
if logger.isEnabledFor(logging.DEBUG):
|
|
||||||
logger.debug("Django found and fields and widgets loaded.")
|
|
||||||
except ImportError:
|
|
||||||
if logger.isEnabledFor(logging.INFO):
|
|
||||||
logger.info("Django not found.")
|
|
||||||
|
|
|
||||||
9
django_select2/apps.py
Normal file
9
django_select2/apps.py
Normal 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'
|
||||||
20
django_select2/cache.py
Normal file
20
django_select2/cache.py
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
"""
|
||||||
|
Shared memory across multiple machines to the heavy AJAX lookups.
|
||||||
|
|
||||||
|
Select2 uses django.core.cache_ to share fields across
|
||||||
|
multiple threads and even machines.
|
||||||
|
|
||||||
|
Select2 uses the cache backend defined in the setting
|
||||||
|
``SELECT2_CACHE_BACKEND`` [default=``default``].
|
||||||
|
|
||||||
|
It is advised to always setup a separate cache server for Select2.
|
||||||
|
|
||||||
|
.. _django.core.cache: https://docs.djangoproject.com/en/dev/topics/cache/
|
||||||
|
"""
|
||||||
|
from django.core.cache import caches
|
||||||
|
|
||||||
|
from .conf import settings
|
||||||
|
|
||||||
|
__all__ = ('cache', )
|
||||||
|
|
||||||
|
cache = caches[settings.SELECT2_CACHE_BACKEND]
|
||||||
180
django_select2/conf.py
Normal file
180
django_select2/conf.py
Normal file
|
|
@ -0,0 +1,180 @@
|
||||||
|
"""Settings for Django-Select2."""
|
||||||
|
from appconf import AppConf
|
||||||
|
from django.conf import settings # NOQA
|
||||||
|
|
||||||
|
__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.
|
||||||
|
|
||||||
|
Example of settings.py::
|
||||||
|
|
||||||
|
CACHES = {
|
||||||
|
"default": {
|
||||||
|
"BACKEND": "django_redis.cache.RedisCache",
|
||||||
|
"LOCATION": "redis://127.0.0.1:6379/1",
|
||||||
|
"OPTIONS": {
|
||||||
|
"CLIENT_CLASS": "django_redis.client.DefaultClient",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'select2': {
|
||||||
|
"BACKEND": "django_redis.cache.RedisCache",
|
||||||
|
"LOCATION": "redis://127.0.0.1:6379/2",
|
||||||
|
"OPTIONS": {
|
||||||
|
"CLIENT_CLASS": "django_redis.client.DefaultClient",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Set the cache backend to select2
|
||||||
|
SELECT2_CACHE_BACKEND = 'select2'
|
||||||
|
|
||||||
|
.. 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 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/{version}/js/select2.min.js'.format(version=LIB_VERSION)
|
||||||
|
"""
|
||||||
|
The URI for the Select2 JS file. By default this points to the Cloudflare CDN.
|
||||||
|
|
||||||
|
If you want to select the version of the JS library used, or want to serve it from
|
||||||
|
the local 'static' resources, add a line to your settings.py like so::
|
||||||
|
|
||||||
|
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/{version}/css/select2.min.css'.format(version=LIB_VERSION)
|
||||||
|
"""
|
||||||
|
The URI for the Select2 CSS file. By default this points to the Cloudflare CDN.
|
||||||
|
|
||||||
|
If you want to select the version of the library used, or want to serve it from
|
||||||
|
the local 'static' resources, add a line to your settings.py like so::
|
||||||
|
|
||||||
|
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'
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
from __future__ import absolute_import, unicode_literals
|
|
||||||
|
|
||||||
from .models import KeyMap
|
|
||||||
|
|
||||||
|
|
||||||
class Client(object):
|
|
||||||
def set(self, key, value):
|
|
||||||
"""
|
|
||||||
This method is used to set a new value
|
|
||||||
in the db.
|
|
||||||
"""
|
|
||||||
o = self.get(key)
|
|
||||||
if o is None:
|
|
||||||
o = KeyMap()
|
|
||||||
o.key = key
|
|
||||||
|
|
||||||
o.value = value
|
|
||||||
o.save()
|
|
||||||
|
|
||||||
def get(self, key):
|
|
||||||
"""
|
|
||||||
This method is used to retrieve a value
|
|
||||||
from the db.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
return KeyMap.objects.get(key=key).value
|
|
||||||
except KeyMap.DoesNotExist:
|
|
||||||
return None
|
|
||||||
|
|
@ -1,884 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
"""
|
|
||||||
Contains all the Django fields for Select2.
|
|
||||||
"""
|
|
||||||
from __future__ import absolute_import, unicode_literals
|
|
||||||
|
|
||||||
import copy
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from django import forms
|
|
||||||
from django.core import validators
|
|
||||||
from django.core.exceptions import ValidationError
|
|
||||||
from django.db.models import Q
|
|
||||||
from django.forms.models import ModelChoiceIterator
|
|
||||||
from django.utils import six
|
|
||||||
from django.utils.encoding import force_text, smart_text
|
|
||||||
from django.utils.translation import ugettext_lazy as _
|
|
||||||
|
|
||||||
from . import util
|
|
||||||
from .util import extract_some_key_val
|
|
||||||
from .views import NO_ERR_RESP
|
|
||||||
from .widgets import AutoHeavySelect2Mixin # NOQA
|
|
||||||
from .widgets import (AutoHeavySelect2MultipleWidget,
|
|
||||||
AutoHeavySelect2TagWidget, AutoHeavySelect2Widget,
|
|
||||||
HeavySelect2MultipleWidget, HeavySelect2TagWidget,
|
|
||||||
HeavySelect2Widget, Select2MultipleWidget, Select2Widget)
|
|
||||||
|
|
||||||
try:
|
|
||||||
from django.forms.fields import RenameFieldMethods as UnhideableQuerysetTypeBase
|
|
||||||
except ImportError:
|
|
||||||
UnhideableQuerysetTypeBase = type
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class AutoViewFieldMixin(object):
|
|
||||||
"""
|
|
||||||
Registers itself with AutoResponseView.
|
|
||||||
|
|
||||||
All Auto fields must sub-class this mixin, so that they are registered.
|
|
||||||
|
|
||||||
.. warning:: Do not forget to include ``'django_select2.urls'`` in your url conf, else,
|
|
||||||
central view used to serve Auto fields won't be available.
|
|
||||||
"""
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
"""
|
|
||||||
Class constructor.
|
|
||||||
|
|
||||||
:param auto_id: The key to use while registering this field. If it is not provided then
|
|
||||||
an auto generated key is used.
|
|
||||||
|
|
||||||
.. tip::
|
|
||||||
This mixin uses full class name of the field to register itself. This is
|
|
||||||
used like key in a :py:obj:`dict` by :py:func:`.util.register_field`.
|
|
||||||
|
|
||||||
If that key already exists then the instance is not registered again. So, eventually
|
|
||||||
all instances of an Auto field share one instance to respond to the Ajax queries for
|
|
||||||
its fields.
|
|
||||||
|
|
||||||
If for some reason any instance needs to be isolated then ``auto_id`` can be used to
|
|
||||||
provide a unique key which has never occured before.
|
|
||||||
|
|
||||||
:type auto_id: :py:obj:`unicode`
|
|
||||||
|
|
||||||
"""
|
|
||||||
name = kwargs.pop('auto_id', "%s.%s" % (self.__module__, self.__class__.__name__))
|
|
||||||
if logger.isEnabledFor(logging.INFO):
|
|
||||||
logger.info("Registering auto field: %s", name)
|
|
||||||
|
|
||||||
rf = util.register_field
|
|
||||||
|
|
||||||
id_ = rf(name, self)
|
|
||||||
self.field_id = id_
|
|
||||||
super(AutoViewFieldMixin, self).__init__(*args, **kwargs)
|
|
||||||
|
|
||||||
def security_check(self, request, *args, **kwargs):
|
|
||||||
"""
|
|
||||||
Returns ``False`` if security check fails.
|
|
||||||
|
|
||||||
:param request: The Ajax request object.
|
|
||||||
:type request: :py:class:`django.http.HttpRequest`
|
|
||||||
|
|
||||||
:param args: The ``*args`` passed to :py:meth:`django.views.generic.base.View.dispatch`.
|
|
||||||
:param kwargs: The ``**kwargs`` passed to :py:meth:`django.views.generic.base.View.dispatch`.
|
|
||||||
|
|
||||||
:return: A boolean value, signalling if check passed or failed.
|
|
||||||
:rtype: :py:obj:`bool`
|
|
||||||
|
|
||||||
.. warning:: Sub-classes should override this. You really do not want random people making
|
|
||||||
Http requests to your server, be able to get access to sensitive information.
|
|
||||||
"""
|
|
||||||
return True
|
|
||||||
|
|
||||||
def get_results(self, request, term, page, context):
|
|
||||||
"""See :py:meth:`.views.Select2View.get_results`."""
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
|
|
||||||
# ## Light general fields ##
|
|
||||||
|
|
||||||
|
|
||||||
class Select2ChoiceField(forms.ChoiceField):
|
|
||||||
"""
|
|
||||||
Drop-in Select2 replacement for :py:class:`forms.ChoiceField`.
|
|
||||||
"""
|
|
||||||
widget = Select2Widget
|
|
||||||
|
|
||||||
|
|
||||||
class Select2MultipleChoiceField(forms.MultipleChoiceField):
|
|
||||||
"""
|
|
||||||
Drop-in Select2 replacement for :py:class:`forms.MultipleChoiceField`.
|
|
||||||
"""
|
|
||||||
widget = Select2MultipleWidget
|
|
||||||
|
|
||||||
|
|
||||||
# ## Model fields related mixins ##
|
|
||||||
|
|
||||||
|
|
||||||
class ModelResultJsonMixin(object):
|
|
||||||
"""
|
|
||||||
Makes ``heavy_data.js`` parsable JSON response for queries on its model.
|
|
||||||
|
|
||||||
On query it uses :py:meth:`.prepare_qs_params` to prepare query attributes
|
|
||||||
which it then passes to ``self.queryset.filter()`` to get the results.
|
|
||||||
|
|
||||||
It is expected that sub-classes will defined a class field variable
|
|
||||||
``search_fields``, which should be a list of field names to search for.
|
|
||||||
|
|
||||||
.. note:: As of version 3.1.3, ``search_fields`` is optional if sub-class
|
|
||||||
overrides ``get_results``.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
"""
|
|
||||||
Class constructor.
|
|
||||||
|
|
||||||
:param queryset: This can be passed as kwarg here or defined as field variable,
|
|
||||||
like ``search_fields``.
|
|
||||||
:type queryset: :py:class:`django.db.models.query.QuerySet` or None
|
|
||||||
|
|
||||||
:param max_results: Maximum number to results to return per Ajax query.
|
|
||||||
:type max_results: :py:obj:`int`
|
|
||||||
|
|
||||||
:param to_field_name: Which field's value should be returned as result tuple's
|
|
||||||
value. (Default is ``pk``, i.e. the id field of the model)
|
|
||||||
:type to_field_name: :py:obj:`str`
|
|
||||||
"""
|
|
||||||
self.max_results = getattr(self, 'max_results', None)
|
|
||||||
self.to_field_name = getattr(self, 'to_field_name', 'pk')
|
|
||||||
|
|
||||||
super(ModelResultJsonMixin, self).__init__(*args, **kwargs)
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
"""
|
|
||||||
Returns the queryset.
|
|
||||||
|
|
||||||
The default implementation returns the ``self.queryset``, which is usually the
|
|
||||||
one set by sub-classes at class-level. However, if that is ``None``
|
|
||||||
then ``ValueError`` is thrown.
|
|
||||||
|
|
||||||
:return: queryset
|
|
||||||
:rtype: :py:class:`django.db.models.query.QuerySet`
|
|
||||||
"""
|
|
||||||
if self.queryset is None:
|
|
||||||
raise ValueError('queryset is required.')
|
|
||||||
|
|
||||||
return self.queryset
|
|
||||||
|
|
||||||
def label_from_instance(self, obj):
|
|
||||||
"""
|
|
||||||
Sub-classes should override this to generate custom label texts for values.
|
|
||||||
|
|
||||||
:param obj: The model object.
|
|
||||||
:type obj: :py:class:`django.model.Model`
|
|
||||||
|
|
||||||
:return: The label string.
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
return smart_text(obj)
|
|
||||||
|
|
||||||
def extra_data_from_instance(self, obj):
|
|
||||||
"""
|
|
||||||
Sub-classes should override this to generate extra data for values. These are passed to
|
|
||||||
JavaScript and can be used for custom rendering.
|
|
||||||
|
|
||||||
:param obj: The model object.
|
|
||||||
:type obj: :py:class:`django.model.Model`
|
|
||||||
|
|
||||||
:return: The extra data dictionary.
|
|
||||||
:rtype: :py:obj:`dict`
|
|
||||||
"""
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def prepare_qs_params(self, request, search_term, search_fields):
|
|
||||||
"""
|
|
||||||
Prepares queryset parameter to use for searching.
|
|
||||||
|
|
||||||
:param search_term: The search term.
|
|
||||||
:type search_term: :py:obj:`str`
|
|
||||||
|
|
||||||
:param search_fields: The list of search fields. This is same as ``self.search_fields``.
|
|
||||||
:type search_term: :py:obj:`list`
|
|
||||||
|
|
||||||
:return: A dictionary of parameters to 'or' and 'and' together. The output format should
|
|
||||||
be ::
|
|
||||||
|
|
||||||
{
|
|
||||||
'or': [
|
|
||||||
Q(attr11=term11) | Q(attr12=term12) | ...,
|
|
||||||
Q(attrN1=termN1) | Q(attrN2=termN2) | ...,
|
|
||||||
...],
|
|
||||||
|
|
||||||
'and': {
|
|
||||||
'attrX1': termX1,
|
|
||||||
'attrX2': termX2,
|
|
||||||
...
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
The above would then be coaxed into ``filter()`` as below::
|
|
||||||
|
|
||||||
queryset.filter(
|
|
||||||
Q(attr11=term11) | Q(attr12=term12) | ...,
|
|
||||||
Q(attrN1=termN1) | Q(attrN2=termN2) | ...,
|
|
||||||
...,
|
|
||||||
attrX1=termX1,
|
|
||||||
attrX2=termX2,
|
|
||||||
...
|
|
||||||
)
|
|
||||||
|
|
||||||
In this implementation, ``term11, term12, termN1, ...`` etc., all are actually ``search_term``.
|
|
||||||
Also then ``and`` part is always empty.
|
|
||||||
|
|
||||||
So, let's take an example.
|
|
||||||
|
|
||||||
| Assume, ``search_term == 'John'``
|
|
||||||
| ``self.search_fields == ['first_name__icontains', 'last_name__icontains']``
|
|
||||||
|
|
||||||
So, the prepared query would be::
|
|
||||||
|
|
||||||
{
|
|
||||||
'or': [
|
|
||||||
Q(first_name__icontains=search_term) | Q(last_name__icontains=search_term)
|
|
||||||
],
|
|
||||||
'and': {}
|
|
||||||
}
|
|
||||||
:rtype: :py:obj:`dict`
|
|
||||||
"""
|
|
||||||
q = None
|
|
||||||
for field in search_fields:
|
|
||||||
kwargs = {}
|
|
||||||
kwargs[field] = search_term
|
|
||||||
if q is None:
|
|
||||||
q = Q(**kwargs)
|
|
||||||
else:
|
|
||||||
q = q | Q(**kwargs)
|
|
||||||
return {'or': [q], 'and': {}}
|
|
||||||
|
|
||||||
def get_results(self, request, term, page, context):
|
|
||||||
"""
|
|
||||||
See :py:meth:`.views.Select2View.get_results`.
|
|
||||||
|
|
||||||
This implementation takes care of detecting if more results are available.
|
|
||||||
"""
|
|
||||||
if not hasattr(self, 'search_fields') or not self.search_fields:
|
|
||||||
raise ValueError('search_fields is required.')
|
|
||||||
|
|
||||||
qs = copy.deepcopy(self.get_queryset())
|
|
||||||
params = self.prepare_qs_params(request, term, self.search_fields)
|
|
||||||
|
|
||||||
if self.max_results:
|
|
||||||
min_ = (page - 1) * self.max_results
|
|
||||||
max_ = min_ + self.max_results + 1 # fetching one extra row to check if it has more rows.
|
|
||||||
res = list(qs.filter(*params['or'], **params['and']).distinct()[min_:max_])
|
|
||||||
has_more = len(res) == (max_ - min_)
|
|
||||||
if has_more:
|
|
||||||
res = res[:-1]
|
|
||||||
else:
|
|
||||||
res = list(qs.filter(*params['or'], **params['and']).distinct())
|
|
||||||
has_more = False
|
|
||||||
|
|
||||||
res = [
|
|
||||||
(
|
|
||||||
getattr(obj, self.to_field_name),
|
|
||||||
self.label_from_instance(obj),
|
|
||||||
self.extra_data_from_instance(obj)
|
|
||||||
)
|
|
||||||
for obj in res
|
|
||||||
]
|
|
||||||
return NO_ERR_RESP, has_more, res
|
|
||||||
|
|
||||||
|
|
||||||
class UnhideableQuerysetType(UnhideableQuerysetTypeBase):
|
|
||||||
"""
|
|
||||||
This does some pretty nasty hacky stuff, to make sure users can
|
|
||||||
also define ``queryset`` as class-level field variable, instead of
|
|
||||||
passing it to constructor.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# TODO check for alternatives. Maybe this hack is not necessary.
|
|
||||||
|
|
||||||
def __new__(cls, name, bases, dct):
|
|
||||||
_q = dct.get('queryset', None)
|
|
||||||
if _q is not None and not isinstance(_q, property):
|
|
||||||
# This hack is needed since users are allowed to
|
|
||||||
# provide queryset in sub-classes by declaring
|
|
||||||
# class variable named - queryset, which will
|
|
||||||
# effectively hide the queryset declared in this
|
|
||||||
# mixin.
|
|
||||||
dct.pop('queryset') # Throwing away the sub-class queryset
|
|
||||||
dct['_subclass_queryset'] = _q
|
|
||||||
|
|
||||||
return type.__new__(cls, name, bases, dct)
|
|
||||||
|
|
||||||
def __call__(cls, *args, **kwargs):
|
|
||||||
queryset = kwargs.get('queryset', None)
|
|
||||||
if queryset is None and hasattr(cls, '_subclass_queryset'):
|
|
||||||
kwargs['queryset'] = getattr(cls, '_subclass_queryset')
|
|
||||||
return type.__call__(cls, *args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
class ChoiceMixin(object):
|
|
||||||
"""
|
|
||||||
Simple mixin which provides a property -- ``choices``. When ``choices`` is set,
|
|
||||||
then it sets that value to ``self.widget.choices`` too.
|
|
||||||
"""
|
|
||||||
def _get_choices(self):
|
|
||||||
if hasattr(self, '_choices'):
|
|
||||||
return self._choices
|
|
||||||
return []
|
|
||||||
|
|
||||||
def _set_choices(self, value):
|
|
||||||
# Setting choices also sets the choices on the widget.
|
|
||||||
# choices can be any iterable, but we call list() on it because
|
|
||||||
# it will be consumed more than once.
|
|
||||||
self._choices = self.widget.choices = list(value)
|
|
||||||
|
|
||||||
choices = property(_get_choices, _set_choices)
|
|
||||||
|
|
||||||
def __deepcopy__(self, memo):
|
|
||||||
result = super(ChoiceMixin, self).__deepcopy__(memo)
|
|
||||||
if hasattr(self, '_choices'):
|
|
||||||
result._choices = copy.deepcopy(self._choices, memo)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
class FilterableModelChoiceIterator(ModelChoiceIterator):
|
|
||||||
"""
|
|
||||||
Extends ModelChoiceIterator to add the capability to apply additional
|
|
||||||
filter on the passed queryset.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def set_extra_filter(self, **filter_map):
|
|
||||||
"""
|
|
||||||
Applies additional filter on the queryset. This can be called multiple times.
|
|
||||||
|
|
||||||
:param filter_map: The ``**kwargs`` to pass to :py:meth:`django.db.models.query.QuerySet.filter`.
|
|
||||||
If this is not set then additional filter (if) applied before is removed.
|
|
||||||
"""
|
|
||||||
if not hasattr(self, '_original_queryset'):
|
|
||||||
import copy
|
|
||||||
self._original_queryset = copy.deepcopy(self.queryset)
|
|
||||||
if filter_map:
|
|
||||||
self.queryset = self._original_queryset.filter(**filter_map)
|
|
||||||
else:
|
|
||||||
self.queryset = self._original_queryset
|
|
||||||
|
|
||||||
|
|
||||||
class QuerysetChoiceMixin(ChoiceMixin):
|
|
||||||
"""
|
|
||||||
Overrides ``choices``' getter to return instance of :py:class:`.FilterableModelChoiceIterator`
|
|
||||||
instead.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def _get_choices(self):
|
|
||||||
# If self._choices is set, then somebody must have manually set
|
|
||||||
# the property self.choices. In this case, just return self._choices.
|
|
||||||
if hasattr(self, '_choices'):
|
|
||||||
return self._choices
|
|
||||||
|
|
||||||
# Otherwise, execute the QuerySet in self.queryset to determine the
|
|
||||||
# choices dynamically. Return a fresh ModelChoiceIterator that has not been
|
|
||||||
# consumed. Note that we're instantiating a new ModelChoiceIterator *each*
|
|
||||||
# time _get_choices() is called (and, thus, each time self.choices is
|
|
||||||
# accessed) so that we can ensure the QuerySet has not been consumed. This
|
|
||||||
# construct might look complicated but it allows for lazy evaluation of
|
|
||||||
# the queryset.
|
|
||||||
return FilterableModelChoiceIterator(self)
|
|
||||||
|
|
||||||
choices = property(_get_choices, ChoiceMixin._set_choices)
|
|
||||||
|
|
||||||
def __deepcopy__(self, memo):
|
|
||||||
result = super(QuerysetChoiceMixin, self).__deepcopy__(memo)
|
|
||||||
# Need to force a new ModelChoiceIterator to be created, bug #11183
|
|
||||||
result.queryset = result.queryset
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
class ModelChoiceFieldMixin(QuerysetChoiceMixin):
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
queryset = kwargs.pop('queryset', None)
|
|
||||||
# This filters out kwargs not supported by Field but are still passed as it is required
|
|
||||||
# by other codes. If new args are added to Field then make sure they are added here too.
|
|
||||||
kargs = extract_some_key_val(kwargs, [
|
|
||||||
'empty_label', 'cache_choices', 'required', 'label', 'initial', 'help_text',
|
|
||||||
'validators', 'localize',
|
|
||||||
])
|
|
||||||
kargs['widget'] = kwargs.pop('widget', getattr(self, 'widget', None))
|
|
||||||
kargs['to_field_name'] = kwargs.pop('to_field_name', 'pk')
|
|
||||||
|
|
||||||
# If it exists then probably it is set by HeavySelect2FieldBase.
|
|
||||||
# We are not gonna use that anyway.
|
|
||||||
if hasattr(self, '_choices'):
|
|
||||||
del self._choices
|
|
||||||
|
|
||||||
super(ModelChoiceFieldMixin, self).__init__(queryset, **kargs)
|
|
||||||
|
|
||||||
if hasattr(self, 'set_placeholder'):
|
|
||||||
self.widget.set_placeholder(self.empty_label)
|
|
||||||
|
|
||||||
def _get_queryset(self):
|
|
||||||
if hasattr(self, '_queryset'):
|
|
||||||
return self._queryset
|
|
||||||
|
|
||||||
def get_pk_field_name(self):
|
|
||||||
return self.to_field_name or 'pk'
|
|
||||||
|
|
||||||
|
|
||||||
# ## Slightly altered versions of the Django counterparts with the same name in forms module. ##
|
|
||||||
|
|
||||||
|
|
||||||
class ModelChoiceField(ModelChoiceFieldMixin, forms.ModelChoiceField):
|
|
||||||
queryset = property(ModelChoiceFieldMixin._get_queryset, forms.ModelChoiceField._set_queryset)
|
|
||||||
|
|
||||||
|
|
||||||
class ModelMultipleChoiceField(ModelChoiceFieldMixin, forms.ModelMultipleChoiceField):
|
|
||||||
queryset = property(ModelChoiceFieldMixin._get_queryset, forms.ModelMultipleChoiceField._set_queryset)
|
|
||||||
|
|
||||||
|
|
||||||
# ## Light Fields specialized for Models ##
|
|
||||||
|
|
||||||
|
|
||||||
class ModelSelect2Field(ModelChoiceField):
|
|
||||||
"""
|
|
||||||
Light Select2 field, specialized for Models.
|
|
||||||
|
|
||||||
Select2 replacement for :py:class:`forms.ModelChoiceField`.
|
|
||||||
"""
|
|
||||||
widget = Select2Widget
|
|
||||||
|
|
||||||
|
|
||||||
class ModelSelect2MultipleField(ModelMultipleChoiceField):
|
|
||||||
"""
|
|
||||||
Light multiple-value Select2 field, specialized for Models.
|
|
||||||
|
|
||||||
Select2 replacement for :py:class:`forms.ModelMultipleChoiceField`.
|
|
||||||
"""
|
|
||||||
widget = Select2MultipleWidget
|
|
||||||
|
|
||||||
|
|
||||||
# ## Heavy fields ##
|
|
||||||
|
|
||||||
|
|
||||||
class HeavySelect2FieldBaseMixin(object):
|
|
||||||
"""
|
|
||||||
Base mixin field for all Heavy fields.
|
|
||||||
|
|
||||||
.. note:: Although Heavy fields accept ``choices`` parameter like all Django choice fields, but these
|
|
||||||
fields are backed by big data sources, so ``choices`` cannot possibly have all the values.
|
|
||||||
|
|
||||||
For Heavies, consider ``choices`` to be a subset of all possible choices. It is available because users
|
|
||||||
might expect it to be available.
|
|
||||||
|
|
||||||
"""
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
"""
|
|
||||||
Class constructor.
|
|
||||||
|
|
||||||
:param data_view: A :py:class:`~.views.Select2View` sub-class which can respond to this widget's Ajax queries.
|
|
||||||
:type data_view: :py:class:`django.views.generic.base.View` or None
|
|
||||||
|
|
||||||
:param widget: A widget instance.
|
|
||||||
:type widget: :py:class:`django.forms.widgets.Widget` or None
|
|
||||||
|
|
||||||
.. warning:: Either of ``data_view`` or ``widget`` must be specified, else :py:exc:`ValueError` would
|
|
||||||
be raised.
|
|
||||||
|
|
||||||
"""
|
|
||||||
data_view = kwargs.pop('data_view', None)
|
|
||||||
choices = kwargs.pop('choices', [])
|
|
||||||
|
|
||||||
kargs = {}
|
|
||||||
if kwargs.get('widget', None) is None:
|
|
||||||
kargs['widget'] = self.widget(data_view=data_view)
|
|
||||||
|
|
||||||
kargs.update(kwargs)
|
|
||||||
super(HeavySelect2FieldBaseMixin, self).__init__(*args, **kargs)
|
|
||||||
|
|
||||||
# By this time self.widget would have been instantiated.
|
|
||||||
|
|
||||||
# This piece of code is needed here since (God knows why) Django's Field class does not call
|
|
||||||
# super(); because of that __init__() of classes would get called after Field.__init__().
|
|
||||||
# If it did had super() call there then we could have simply moved AutoViewFieldMixin at the
|
|
||||||
# end of the MRO list. This way it would have got widget instance instead of class and it
|
|
||||||
# could have directly set field_id on it.
|
|
||||||
if hasattr(self, 'field_id'):
|
|
||||||
self.widget.field_id = self.field_id
|
|
||||||
self.widget.attrs['data-select2-id'] = self.field_id
|
|
||||||
|
|
||||||
# Widget should have been instantiated by now.
|
|
||||||
self.widget.field = self
|
|
||||||
|
|
||||||
# ModelChoiceField will set self.choices to ModelChoiceIterator
|
|
||||||
if choices and not (hasattr(self, 'choices') and isinstance(self.choices, forms.models.ModelChoiceIterator)):
|
|
||||||
self.choices = choices
|
|
||||||
|
|
||||||
|
|
||||||
class HeavyChoiceField(ChoiceMixin, forms.Field):
|
|
||||||
"""
|
|
||||||
Reimplements :py:class:`django.forms.TypedChoiceField` in a way which suites the use of big data.
|
|
||||||
|
|
||||||
.. note:: Although this field accepts ``choices`` parameter like all Django choice fields, but these
|
|
||||||
fields are backed by big data sources, so ``choices`` cannot possibly have all the values. It is meant
|
|
||||||
to be a subset of all possible choices.
|
|
||||||
"""
|
|
||||||
default_error_messages = {
|
|
||||||
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
|
|
||||||
}
|
|
||||||
empty_value = ''
|
|
||||||
"Sub-classes can set this other value if needed."
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
super(HeavyChoiceField, self).__init__(*args, **kwargs)
|
|
||||||
# Widget should have been instantiated by now.
|
|
||||||
self.widget.field = self
|
|
||||||
|
|
||||||
def to_python(self, value):
|
|
||||||
if value == self.empty_value or value in validators.EMPTY_VALUES:
|
|
||||||
return self.empty_value
|
|
||||||
try:
|
|
||||||
value = self.coerce_value(value)
|
|
||||||
except (ValueError, TypeError, ValidationError):
|
|
||||||
raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
|
|
||||||
return value
|
|
||||||
|
|
||||||
def validate(self, value):
|
|
||||||
super(HeavyChoiceField, self).validate(value)
|
|
||||||
if value and not self.valid_value(value):
|
|
||||||
raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
|
|
||||||
|
|
||||||
def valid_value(self, value):
|
|
||||||
uvalue = smart_text(value)
|
|
||||||
for k, v in self.choices:
|
|
||||||
if uvalue == smart_text(k):
|
|
||||||
return True
|
|
||||||
return self.validate_value(value)
|
|
||||||
|
|
||||||
def coerce_value(self, value):
|
|
||||||
"""
|
|
||||||
Coerces ``value`` to a Python data type.
|
|
||||||
|
|
||||||
Sub-classes should override this if they do not want Unicode values.
|
|
||||||
"""
|
|
||||||
return smart_text(value)
|
|
||||||
|
|
||||||
def validate_value(self, value):
|
|
||||||
"""
|
|
||||||
Sub-classes can override this to validate the value entered against the big data.
|
|
||||||
|
|
||||||
:param value: Value entered by the user.
|
|
||||||
:type value: As coerced by :py:meth:`.coerce_value`.
|
|
||||||
|
|
||||||
:return: ``True`` means the ``value`` is valid.
|
|
||||||
"""
|
|
||||||
return True
|
|
||||||
|
|
||||||
def _get_val_txt(self, value):
|
|
||||||
try:
|
|
||||||
value = self.coerce_value(value)
|
|
||||||
self.validate_value(value)
|
|
||||||
except Exception:
|
|
||||||
logger.exception("Exception while trying to get label for value")
|
|
||||||
return None
|
|
||||||
return self.get_val_txt(value)
|
|
||||||
|
|
||||||
def get_val_txt(self, value):
|
|
||||||
"""
|
|
||||||
If Heavy widgets encounter any value which it can't find in ``choices`` then it calls
|
|
||||||
this method to get the label for the value.
|
|
||||||
|
|
||||||
:param value: Value entered by the user.
|
|
||||||
:type value: As coerced by :py:meth:`.coerce_value`.
|
|
||||||
|
|
||||||
:return: The label for this value.
|
|
||||||
:rtype: :py:obj:`unicode` or None (when no possible label could be found)
|
|
||||||
"""
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
class HeavyMultipleChoiceField(HeavyChoiceField):
|
|
||||||
"""
|
|
||||||
Reimplements :py:class:`django.forms.TypedMultipleChoiceField` in a way which suites the use of big data.
|
|
||||||
|
|
||||||
.. note:: Although this field accepts ``choices`` parameter like all Django choice fields, but these
|
|
||||||
fields are backed by big data sources, so ``choices`` cannot possibly have all the values. It is meant
|
|
||||||
to be a subset of all possible choices.
|
|
||||||
"""
|
|
||||||
hidden_widget = forms.MultipleHiddenInput
|
|
||||||
default_error_messages = {
|
|
||||||
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
|
|
||||||
'invalid_list': _('Enter a list of values.'),
|
|
||||||
}
|
|
||||||
|
|
||||||
def to_python(self, value):
|
|
||||||
if not value:
|
|
||||||
return []
|
|
||||||
elif not isinstance(value, (list, tuple)):
|
|
||||||
raise ValidationError(self.error_messages['invalid_list'])
|
|
||||||
return [self.coerce_value(val) for val in value]
|
|
||||||
|
|
||||||
def validate(self, value):
|
|
||||||
if self.required and not value:
|
|
||||||
raise ValidationError(self.error_messages['required'])
|
|
||||||
# Validate that each value in the value list is in self.choices or
|
|
||||||
# the big data (i.e. validate_value() returns True).
|
|
||||||
for val in value:
|
|
||||||
if not self.valid_value(val):
|
|
||||||
raise ValidationError(self.error_messages['invalid_choice'] % {'value': val})
|
|
||||||
|
|
||||||
|
|
||||||
class HeavySelect2ChoiceField(HeavySelect2FieldBaseMixin, HeavyChoiceField):
|
|
||||||
"""Heavy Select2 Choice field."""
|
|
||||||
widget = HeavySelect2Widget
|
|
||||||
|
|
||||||
|
|
||||||
class HeavySelect2MultipleChoiceField(HeavySelect2FieldBaseMixin, HeavyMultipleChoiceField):
|
|
||||||
"""Heavy Select2 Multiple Choice field."""
|
|
||||||
widget = HeavySelect2MultipleWidget
|
|
||||||
|
|
||||||
|
|
||||||
class HeavySelect2TagField(HeavySelect2MultipleChoiceField):
|
|
||||||
"""
|
|
||||||
Heavy Select2 field for tagging.
|
|
||||||
|
|
||||||
.. warning:: :py:exc:`NotImplementedError` would be thrown if :py:meth:`create_new_value` is not implemented.
|
|
||||||
"""
|
|
||||||
widget = HeavySelect2TagWidget
|
|
||||||
|
|
||||||
def validate(self, value):
|
|
||||||
if self.required and not value:
|
|
||||||
raise ValidationError(self.error_messages['required'])
|
|
||||||
# Check if each value in the value list is in self.choices or
|
|
||||||
# the big data (i.e. validate_value() returns True).
|
|
||||||
# If not then calls create_new_value() to create the new value.
|
|
||||||
for i in range(0, len(value)):
|
|
||||||
val = value[i]
|
|
||||||
if not self.valid_value(val):
|
|
||||||
value[i] = self.create_new_value(val)
|
|
||||||
|
|
||||||
def create_new_value(self, value):
|
|
||||||
"""
|
|
||||||
This is called when the input value is not valid. This
|
|
||||||
allows you to add the value into the data-store. If that
|
|
||||||
is not done then eventually the validation will fail.
|
|
||||||
|
|
||||||
:param value: Invalid value entered by the user.
|
|
||||||
:type value: As coerced by :py:meth:`HeavyChoiceField.coerce_value`.
|
|
||||||
|
|
||||||
:return: The a new value, which could be the id (pk) of the created value.
|
|
||||||
:rtype: Any
|
|
||||||
"""
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
|
|
||||||
# ## Heavy field specialized for Models ##
|
|
||||||
|
|
||||||
|
|
||||||
class HeavyModelSelect2ChoiceField(HeavySelect2FieldBaseMixin, ModelChoiceField):
|
|
||||||
"""Heavy Select2 Choice field, specialized for Models."""
|
|
||||||
widget = HeavySelect2Widget
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
kwargs.pop('choices', None)
|
|
||||||
super(HeavyModelSelect2ChoiceField, self).__init__(*args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
class HeavyModelSelect2MultipleChoiceField(HeavySelect2FieldBaseMixin, ModelMultipleChoiceField):
|
|
||||||
"""Heavy Select2 Multiple Choice field, specialized for Models."""
|
|
||||||
widget = HeavySelect2MultipleWidget
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
kwargs.pop('choices', None)
|
|
||||||
super(HeavyModelSelect2MultipleChoiceField, self).__init__(*args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
class HeavyModelSelect2TagField(HeavySelect2FieldBaseMixin, ModelMultipleChoiceField):
|
|
||||||
"""
|
|
||||||
Heavy Select2 field for tagging, specialized for Models.
|
|
||||||
|
|
||||||
.. warning:: :py:exc:`NotImplementedError` would be thrown if :py:meth:`get_model_field_values` is not implemented.
|
|
||||||
"""
|
|
||||||
widget = HeavySelect2TagWidget
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
kwargs.pop('choices', None)
|
|
||||||
super(HeavyModelSelect2TagField, self).__init__(*args, **kwargs)
|
|
||||||
|
|
||||||
def to_python(self, value):
|
|
||||||
if value in self.empty_values:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
key = self.to_field_name or 'pk'
|
|
||||||
value = self.queryset.get(**{key: value})
|
|
||||||
except ValueError:
|
|
||||||
raise ValidationError(self.error_messages['invalid_choice'])
|
|
||||||
except self.queryset.model.DoesNotExist:
|
|
||||||
value = self.create_new_value(value)
|
|
||||||
return value
|
|
||||||
|
|
||||||
def clean(self, value):
|
|
||||||
if self.required and not value:
|
|
||||||
raise ValidationError(self.error_messages['required'])
|
|
||||||
elif not self.required and not value:
|
|
||||||
return []
|
|
||||||
if not isinstance(value, (list, tuple)):
|
|
||||||
raise ValidationError(self.error_messages['list'])
|
|
||||||
new_values = []
|
|
||||||
key = self.to_field_name or 'pk'
|
|
||||||
for pk in list(value):
|
|
||||||
try:
|
|
||||||
self.queryset.filter(**{key: pk})
|
|
||||||
except ValueError:
|
|
||||||
value.remove(pk)
|
|
||||||
new_values.append(pk)
|
|
||||||
|
|
||||||
for val in new_values:
|
|
||||||
value.append(self.create_new_value(force_text(val)))
|
|
||||||
|
|
||||||
# Usually new_values will have list of new tags, but if the tag is
|
|
||||||
# suppose of type int then that could be interpreted as valid pk
|
|
||||||
# value and ValueError above won't be triggered.
|
|
||||||
# Below we find such tags and create them, by check if the pk
|
|
||||||
# actually exists.
|
|
||||||
qs = self.queryset.filter(**{'%s__in' % key: value})
|
|
||||||
pks = set([force_text(getattr(o, key)) for o in qs])
|
|
||||||
for i in range(0, len(value)):
|
|
||||||
val = force_text(value[i])
|
|
||||||
if val not in pks:
|
|
||||||
value[i] = self.create_new_value(val)
|
|
||||||
# Since this overrides the inherited ModelChoiceField.clean
|
|
||||||
# we run custom validators here
|
|
||||||
self.run_validators(value)
|
|
||||||
return qs
|
|
||||||
|
|
||||||
def create_new_value(self, value):
|
|
||||||
"""
|
|
||||||
This is called when the input value is not valid. This
|
|
||||||
allows you to add the value into the data-store. If that
|
|
||||||
is not done then eventually the validation will fail.
|
|
||||||
|
|
||||||
:param value: Invalid value entered by the user.
|
|
||||||
:type value: As coerced by :py:meth:`HeavyChoiceField.coerce_value`.
|
|
||||||
|
|
||||||
:return: The a new value, which could be the id (pk) of the created value.
|
|
||||||
:rtype: Any
|
|
||||||
"""
|
|
||||||
obj = self.queryset.create(**self.get_model_field_values(value))
|
|
||||||
return getattr(obj, self.to_field_name or 'pk')
|
|
||||||
|
|
||||||
def get_model_field_values(self, value):
|
|
||||||
"""
|
|
||||||
This is called when the input value is not valid and the field
|
|
||||||
tries to create a new model instance.
|
|
||||||
|
|
||||||
:param value: Invalid value entered by the user.
|
|
||||||
:type value: unicode
|
|
||||||
|
|
||||||
:return: Dict with attribute name - attribute value pair.
|
|
||||||
:rtype: dict
|
|
||||||
"""
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
# ## Heavy general field that uses central AutoView ##
|
|
||||||
|
|
||||||
|
|
||||||
class AutoSelect2Field(AutoViewFieldMixin, HeavySelect2ChoiceField):
|
|
||||||
"""
|
|
||||||
Auto Heavy Select2 field.
|
|
||||||
|
|
||||||
This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming
|
|
||||||
json query requests for that type (class).
|
|
||||||
|
|
||||||
.. warning:: :py:exc:`NotImplementedError` would be thrown if :py:meth:`get_results` is not implemented.
|
|
||||||
"""
|
|
||||||
|
|
||||||
widget = AutoHeavySelect2Widget
|
|
||||||
|
|
||||||
|
|
||||||
class AutoSelect2MultipleField(AutoViewFieldMixin, HeavySelect2MultipleChoiceField):
|
|
||||||
"""
|
|
||||||
Auto Heavy Select2 field for multiple choices.
|
|
||||||
|
|
||||||
This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming
|
|
||||||
json query requests for that type (class).
|
|
||||||
|
|
||||||
.. warning:: :py:exc:`NotImplementedError` would be thrown if :py:meth:`get_results` is not implemented.
|
|
||||||
"""
|
|
||||||
|
|
||||||
widget = AutoHeavySelect2MultipleWidget
|
|
||||||
|
|
||||||
|
|
||||||
class AutoSelect2TagField(AutoViewFieldMixin, HeavySelect2TagField):
|
|
||||||
"""
|
|
||||||
Auto Heavy Select2 field for tagging.
|
|
||||||
|
|
||||||
This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming
|
|
||||||
json query requests for that type (class).
|
|
||||||
|
|
||||||
.. warning:: :py:exc:`NotImplementedError` would be thrown if :py:meth:`get_results` is not implemented.
|
|
||||||
"""
|
|
||||||
|
|
||||||
widget = AutoHeavySelect2TagWidget
|
|
||||||
|
|
||||||
|
|
||||||
# ## Heavy field, specialized for Model, that uses central AutoView ##
|
|
||||||
|
|
||||||
|
|
||||||
class AutoModelSelect2Field(six.with_metaclass(UnhideableQuerysetType,
|
|
||||||
ModelResultJsonMixin,
|
|
||||||
AutoViewFieldMixin,
|
|
||||||
HeavyModelSelect2ChoiceField)):
|
|
||||||
"""
|
|
||||||
Auto Heavy Select2 field, specialized for Models.
|
|
||||||
|
|
||||||
This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming
|
|
||||||
json query requests for that type (class).
|
|
||||||
"""
|
|
||||||
|
|
||||||
widget = AutoHeavySelect2Widget
|
|
||||||
|
|
||||||
|
|
||||||
class AutoModelSelect2MultipleField(six.with_metaclass(UnhideableQuerysetType,
|
|
||||||
ModelResultJsonMixin,
|
|
||||||
AutoViewFieldMixin,
|
|
||||||
HeavyModelSelect2MultipleChoiceField)):
|
|
||||||
"""
|
|
||||||
Auto Heavy Select2 field for multiple choices, specialized for Models.
|
|
||||||
|
|
||||||
This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming
|
|
||||||
json query requests for that type (class).
|
|
||||||
"""
|
|
||||||
|
|
||||||
widget = AutoHeavySelect2MultipleWidget
|
|
||||||
|
|
||||||
|
|
||||||
class AutoModelSelect2TagField(six.with_metaclass(UnhideableQuerysetType,
|
|
||||||
ModelResultJsonMixin,
|
|
||||||
AutoViewFieldMixin,
|
|
||||||
HeavyModelSelect2TagField)):
|
|
||||||
"""
|
|
||||||
Auto Heavy Select2 field for tagging, specialized for Models.
|
|
||||||
|
|
||||||
This needs to be subclassed. The first instance of a class (sub-class) is used to serve all incoming
|
|
||||||
json query requests for that type (class).
|
|
||||||
|
|
||||||
.. warning:: :py:exc:`NotImplementedError` would be thrown if :py:meth:`get_model_field_values` is not implemented.
|
|
||||||
|
|
||||||
Example::
|
|
||||||
|
|
||||||
class Tag(models.Model):
|
|
||||||
tag = models.CharField(max_length=10, unique=True)
|
|
||||||
def __str__(self):
|
|
||||||
return text_type(self.tag)
|
|
||||||
|
|
||||||
class TagField(AutoModelSelect2TagField):
|
|
||||||
queryset = Tag.objects
|
|
||||||
search_fields = ['tag__icontains', ]
|
|
||||||
def get_model_field_values(self, value):
|
|
||||||
return {'tag': value}
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
widget = AutoHeavySelect2TagWidget
|
|
||||||
580
django_select2/forms.py
Normal file
580
django_select2/forms.py
Normal file
|
|
@ -0,0 +1,580 @@
|
||||||
|
"""
|
||||||
|
Django-Select2 Widgets.
|
||||||
|
|
||||||
|
These components are responsible for rendering
|
||||||
|
the necessary HTML data markups. Since this whole
|
||||||
|
package is to render choices using Select2 JavaScript
|
||||||
|
library, hence these components are meant to be used
|
||||||
|
with choice fields.
|
||||||
|
|
||||||
|
Widgets are generally of two types:
|
||||||
|
|
||||||
|
1. **Light** --
|
||||||
|
They are not meant to be used when there
|
||||||
|
are too many options, say, in thousands.
|
||||||
|
This is because all those options would
|
||||||
|
have to be pre-rendered onto the page
|
||||||
|
and JavaScript would be used to search
|
||||||
|
through them. Said that, they are also one
|
||||||
|
the most easiest to use. They are a
|
||||||
|
drop-in-replacement for Django's default
|
||||||
|
select widgets.
|
||||||
|
|
||||||
|
2(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,
|
||||||
|
so you need not worry about writing any Ajax related JS code.
|
||||||
|
Although on the server side you do need to create a view
|
||||||
|
specifically to respond to the queries.
|
||||||
|
|
||||||
|
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 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 functools import reduce
|
||||||
|
from itertools import chain
|
||||||
|
from pickle import PicklingError # nosec
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
from django.contrib.admin.widgets import SELECT2_TRANSLATIONS
|
||||||
|
from django.core import signing
|
||||||
|
from django.db.models import Q
|
||||||
|
from django.forms.models import ModelChoiceIterator
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils.translation import get_language
|
||||||
|
|
||||||
|
from .cache import cache
|
||||||
|
from .conf import settings
|
||||||
|
|
||||||
|
|
||||||
|
class Select2Mixin:
|
||||||
|
"""
|
||||||
|
The base mixin of all Select2 widgets.
|
||||||
|
|
||||||
|
This mixin is responsible for rendering the necessary
|
||||||
|
data attributes for select2 as well as adding the static
|
||||||
|
form media.
|
||||||
|
"""
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
if 'class' in attrs:
|
||||||
|
attrs['class'] += ' django-select2'
|
||||||
|
else:
|
||||||
|
attrs['class'] = 'django-select2'
|
||||||
|
return attrs
|
||||||
|
|
||||||
|
def optgroups(self, name, value, attrs=None):
|
||||||
|
"""Add empty option for clearable selects."""
|
||||||
|
if not self.is_required and not self.allow_multiple_selected:
|
||||||
|
self.choices = list(chain([('', '')], self.choices))
|
||||||
|
return super(Select2Mixin, self).optgroups(name, value, attrs=attrs)
|
||||||
|
|
||||||
|
def _get_media(self):
|
||||||
|
"""
|
||||||
|
Construct Media as a dynamic property.
|
||||||
|
|
||||||
|
.. Note:: For more information visit
|
||||||
|
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=select2_js + i18n_file + ('django_select2/django_select2.js',),
|
||||||
|
css={'screen': select2_css}
|
||||||
|
)
|
||||||
|
|
||||||
|
media = property(_get_media)
|
||||||
|
|
||||||
|
|
||||||
|
class Select2TagMixin:
|
||||||
|
"""Mixin to add select2 tag functionality."""
|
||||||
|
|
||||||
|
def build_attrs(self, base_attrs, extra_attrs=None):
|
||||||
|
"""Add select2's tag attributes."""
|
||||||
|
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):
|
||||||
|
"""
|
||||||
|
Select2 drop in widget.
|
||||||
|
|
||||||
|
Example usage::
|
||||||
|
|
||||||
|
class MyModelForm(forms.ModelForm):
|
||||||
|
class Meta:
|
||||||
|
model = MyModel
|
||||||
|
fields = ('my_field', )
|
||||||
|
widgets = {
|
||||||
|
'my_field': Select2Widget
|
||||||
|
}
|
||||||
|
|
||||||
|
or::
|
||||||
|
|
||||||
|
class MyForm(forms.Form):
|
||||||
|
my_choice = forms.ChoiceField(widget=Select2Widget)
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Select2MultipleWidget(Select2Mixin, forms.SelectMultiple):
|
||||||
|
"""
|
||||||
|
Select2 drop in widget for multiple select.
|
||||||
|
|
||||||
|
Works just like :class:`.Select2Widget` but for multi select.
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Select2TagWidget(Select2TagMixin, Select2Mixin, forms.SelectMultiple):
|
||||||
|
"""
|
||||||
|
Select2 drop in widget for for tagging.
|
||||||
|
|
||||||
|
Example for :class:`.django.contrib.postgres.fields.ArrayField`::
|
||||||
|
|
||||||
|
class MyWidget(Select2TagWidget):
|
||||||
|
|
||||||
|
def value_from_datadict(self, data, files, name):
|
||||||
|
values = super(MyWidget, self).value_from_datadict(data, files, name):
|
||||||
|
return ",".join(values)
|
||||||
|
|
||||||
|
def optgroups(self, name, value, attrs=None):
|
||||||
|
values = value[0].split(',') if value[0] else []
|
||||||
|
selected = set(values)
|
||||||
|
subgroup = [self.create_option(name, v, v, selected, i) for i, v in enumerate(values)]
|
||||||
|
return [(None, subgroup, 0)]
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class HeavySelect2Mixin:
|
||||||
|
"""Mixin that adds select2's AJAX options and registers itself on Django's cache."""
|
||||||
|
|
||||||
|
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')
|
||||||
|
|
||||||
|
def get_url(self):
|
||||||
|
"""Return URL from instance or by reversing :attr:`.data_view`."""
|
||||||
|
if self.data_url:
|
||||||
|
return self.data_url
|
||||||
|
return reverse(self.data_view)
|
||||||
|
|
||||||
|
def build_attrs(self, base_attrs, extra_attrs=None):
|
||||||
|
"""Set select2's AJAX attributes."""
|
||||||
|
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['class'] += ' django-select2-heavy'
|
||||||
|
return attrs
|
||||||
|
|
||||||
|
def render(self, *args, **kwargs):
|
||||||
|
"""Render widget and register it in Django's cache."""
|
||||||
|
output = super(HeavySelect2Mixin, self).render(*args, **kwargs)
|
||||||
|
self.set_to_cache()
|
||||||
|
return output
|
||||||
|
|
||||||
|
def _get_cache_key(self):
|
||||||
|
return "%s%s" % (settings.SELECT2_CACHE_PREFIX, id(self))
|
||||||
|
|
||||||
|
def set_to_cache(self):
|
||||||
|
"""
|
||||||
|
Add widget object to Django's cache.
|
||||||
|
|
||||||
|
You may need to overwrite this method, to pickle all information
|
||||||
|
that is required to serve your JSON response view.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
cache.set(self._get_cache_key(), {
|
||||||
|
'widget': self,
|
||||||
|
'url': self.get_url(),
|
||||||
|
})
|
||||||
|
except (PicklingError, AttributeError):
|
||||||
|
msg = "You need to overwrite \"set_to_cache\" or ensure that %s is serialisable."
|
||||||
|
raise NotImplementedError(msg % self.__class__.__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class HeavySelect2Widget(HeavySelect2Mixin, Select2Widget):
|
||||||
|
"""
|
||||||
|
Select2 widget with AJAX support that registers itself to Django's Cache.
|
||||||
|
|
||||||
|
Usage example::
|
||||||
|
|
||||||
|
class MyWidget(HeavySelect2Widget):
|
||||||
|
data_view = 'my_view_name'
|
||||||
|
|
||||||
|
or::
|
||||||
|
|
||||||
|
class MyForm(forms.Form):
|
||||||
|
my_field = forms.ChoiceField(
|
||||||
|
widget=HeavySelect2Widget(
|
||||||
|
data_url='/url/to/json/response'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class HeavySelect2MultipleWidget(HeavySelect2Mixin, Select2MultipleWidget):
|
||||||
|
"""Select2 multi select widget similar to :class:`.HeavySelect2Widget`."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class HeavySelect2TagWidget(HeavySelect2Mixin, Select2TagWidget):
|
||||||
|
"""Select2 tag widget."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Auto Heavy widgets
|
||||||
|
|
||||||
|
|
||||||
|
class ModelSelect2Mixin:
|
||||||
|
"""Widget mixin that provides attributes and methods for :class:`.AutoResponseView`."""
|
||||||
|
|
||||||
|
model = None
|
||||||
|
queryset = None
|
||||||
|
search_fields = []
|
||||||
|
"""
|
||||||
|
Model lookups that are used to filter the QuerySet.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
search_fields = [
|
||||||
|
'title__icontains',
|
||||||
|
]
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
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.query.QuerySet): QuerySet to select choices from.
|
||||||
|
search_fields (list): List of model lookup strings.
|
||||||
|
max_results (int): Max. JsonResponse view page size.
|
||||||
|
|
||||||
|
"""
|
||||||
|
self.model = kwargs.pop('model', self.model)
|
||||||
|
self.queryset = kwargs.pop('queryset', self.queryset)
|
||||||
|
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:auto-json'}
|
||||||
|
defaults.update(kwargs)
|
||||||
|
super(ModelSelect2Mixin, self).__init__(*args, **defaults)
|
||||||
|
|
||||||
|
def set_to_cache(self):
|
||||||
|
"""
|
||||||
|
Add widget's attributes to Django's cache.
|
||||||
|
|
||||||
|
Split the QuerySet, to not pickle the result set.
|
||||||
|
"""
|
||||||
|
queryset = self.get_queryset()
|
||||||
|
cache.set(self._get_cache_key(), {
|
||||||
|
'queryset':
|
||||||
|
[
|
||||||
|
queryset.none(),
|
||||||
|
queryset.query,
|
||||||
|
],
|
||||||
|
'cls': self.__class__,
|
||||||
|
'search_fields': 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, 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
|
||||||
|
|
||||||
|
"""
|
||||||
|
if queryset is None:
|
||||||
|
queryset = self.get_queryset()
|
||||||
|
search_fields = self.get_search_fields()
|
||||||
|
select = Q()
|
||||||
|
term = term.replace('\t', ' ')
|
||||||
|
term = term.replace('\n', ' ')
|
||||||
|
for t in [t for t in term.split(' ') if not t == '']:
|
||||||
|
select &= reduce(lambda x, y: x | Q(**{y: t}), search_fields[1:],
|
||||||
|
Q(**{search_fields[0]: t}))
|
||||||
|
if dependent_fields:
|
||||||
|
select &= Q(**dependent_fields)
|
||||||
|
|
||||||
|
return queryset.filter(select).distinct()
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
"""
|
||||||
|
Return QuerySet based on :attr:`.queryset` or :attr:`.model`.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
QuerySet: QuerySet of available choices.
|
||||||
|
|
||||||
|
"""
|
||||||
|
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:
|
||||||
|
raise NotImplementedError(
|
||||||
|
"%(cls)s is missing a QuerySet. Define "
|
||||||
|
"%(cls)s.model, %(cls)s.queryset, or override "
|
||||||
|
"%(cls)s.get_queryset()." % {
|
||||||
|
'cls': self.__class__.__name__
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return queryset
|
||||||
|
|
||||||
|
def get_search_fields(self):
|
||||||
|
"""Return list of lookup names."""
|
||||||
|
if self.search_fields:
|
||||||
|
return self.search_fields
|
||||||
|
raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__)
|
||||||
|
|
||||||
|
def optgroups(self, name, value, attrs=None):
|
||||||
|
"""Return only selected options and set QuerySet from `ModelChoicesIterator`."""
|
||||||
|
default = (None, [], 0)
|
||||||
|
groups = [default]
|
||||||
|
has_selected = False
|
||||||
|
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):
|
||||||
|
"""
|
||||||
|
Return option label representation from instance.
|
||||||
|
|
||||||
|
Can be overridden to change the representation of each choice.
|
||||||
|
|
||||||
|
Example usage::
|
||||||
|
|
||||||
|
class MyWidget(ModelSelect2Widget):
|
||||||
|
def label_from_instance(obj):
|
||||||
|
return str(obj.title).upper()
|
||||||
|
|
||||||
|
Args:
|
||||||
|
obj (django.db.models.Model): Instance of Django Model.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: Option label.
|
||||||
|
|
||||||
|
"""
|
||||||
|
return str(obj)
|
||||||
|
|
||||||
|
|
||||||
|
class ModelSelect2Widget(ModelSelect2Mixin, HeavySelect2Widget):
|
||||||
|
"""
|
||||||
|
Select2 drop in model select widget.
|
||||||
|
|
||||||
|
Example usage::
|
||||||
|
|
||||||
|
class MyWidget(ModelSelect2Widget):
|
||||||
|
search_fields = [
|
||||||
|
'title__icontains',
|
||||||
|
]
|
||||||
|
|
||||||
|
class MyModelForm(forms.ModelForm):
|
||||||
|
class Meta:
|
||||||
|
model = MyModel
|
||||||
|
fields = ('my_field', )
|
||||||
|
widgets = {
|
||||||
|
'my_field': MyWidget,
|
||||||
|
}
|
||||||
|
|
||||||
|
or::
|
||||||
|
|
||||||
|
class MyForm(forms.Form):
|
||||||
|
my_choice = forms.ChoiceField(
|
||||||
|
widget=ModelSelect2Widget(
|
||||||
|
model=MyOtherModel,
|
||||||
|
search_fields=['title__icontains']
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
.. tip:: The ModelSelect2(Multiple)Widget will try
|
||||||
|
to get the QuerySet from the fields choices.
|
||||||
|
Therefore you don't need to define a QuerySet,
|
||||||
|
if you just drop in the widget for a ForeignKey field.
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ModelSelect2MultipleWidget(ModelSelect2Mixin, HeavySelect2MultipleWidget):
|
||||||
|
"""
|
||||||
|
Select2 drop in model multiple select widget.
|
||||||
|
|
||||||
|
Works just like :class:`.ModelSelect2Widget` but for multi select.
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ModelSelect2TagWidget(ModelSelect2Mixin, HeavySelect2TagWidget):
|
||||||
|
"""
|
||||||
|
Select2 model widget with tag support.
|
||||||
|
|
||||||
|
This it not a simple drop in widget.
|
||||||
|
It requires to implement you own :func:`.value_from_datadict`
|
||||||
|
that adds missing tags to you QuerySet.
|
||||||
|
|
||||||
|
Example::
|
||||||
|
|
||||||
|
class MyModelSelect2TagWidget(ModelSelect2TagWidget):
|
||||||
|
queryset = MyModel.objects.all()
|
||||||
|
|
||||||
|
def value_from_datadict(self, data, files, name):
|
||||||
|
'''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
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
from django.conf import settings
|
|
||||||
from django.contrib.staticfiles.templatetags.staticfiles import static
|
|
||||||
|
|
||||||
from . import __BOOTSTRAP as BOOTSTRAP
|
|
||||||
|
|
||||||
# Local version of DEBUG
|
|
||||||
DEBUG = settings.configured and settings.DEBUG
|
|
||||||
|
|
||||||
|
|
||||||
def django_select2_static(file):
|
|
||||||
return static('django_select2/' + file)
|
|
||||||
|
|
||||||
|
|
||||||
def get_select2_js_libs():
|
|
||||||
if DEBUG:
|
|
||||||
js_file = 'js/select2.js'
|
|
||||||
else:
|
|
||||||
js_file = 'js/select2.min.js'
|
|
||||||
return (django_select2_static(js_file), )
|
|
||||||
|
|
||||||
|
|
||||||
def get_select2_heavy_js_libs():
|
|
||||||
libs = get_select2_js_libs()
|
|
||||||
|
|
||||||
if DEBUG:
|
|
||||||
js_file = 'js/heavy_data.js'
|
|
||||||
else:
|
|
||||||
js_file = 'js/heavy_data.min.js'
|
|
||||||
return libs + (django_select2_static(js_file), )
|
|
||||||
|
|
||||||
|
|
||||||
def get_select2_css_libs(light=False):
|
|
||||||
css_files = []
|
|
||||||
if BOOTSTRAP:
|
|
||||||
if DEBUG:
|
|
||||||
if light:
|
|
||||||
css_files = ('css/select2.css', 'css/select2-bootstrap.css', )
|
|
||||||
else:
|
|
||||||
css_files = ('css/select2.css', 'css/extra.css', 'css/select2-bootstrap.css')
|
|
||||||
else:
|
|
||||||
if light:
|
|
||||||
css_files = ('css/select2-bootstrapped.min.css',)
|
|
||||||
else:
|
|
||||||
css_files = ('css/all-bootstrapped.min.css',)
|
|
||||||
else:
|
|
||||||
if settings.configured and settings.DEBUG:
|
|
||||||
if light:
|
|
||||||
css_files = ('css/select2.css',)
|
|
||||||
else:
|
|
||||||
css_files = ('css/select2.css', 'css/extra.css')
|
|
||||||
else:
|
|
||||||
if light:
|
|
||||||
css_files = ('css/select2.min.css',)
|
|
||||||
else:
|
|
||||||
css_files = ('css/all.min.css',)
|
|
||||||
return [django_select2_static(f) for f in css_files]
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
from __future__ import absolute_import, unicode_literals
|
|
||||||
|
|
||||||
from django.utils.six import binary_type
|
|
||||||
|
|
||||||
import memcache
|
|
||||||
|
|
||||||
|
|
||||||
class Client(object):
|
|
||||||
host = ""
|
|
||||||
server = ""
|
|
||||||
expiry = 900
|
|
||||||
|
|
||||||
def __init__(self, hostname="127.0.0.1", port="11211", expiry=900):
|
|
||||||
self.host = "%s:%s" % (hostname, port)
|
|
||||||
self.server = memcache.Client([self.host])
|
|
||||||
self.expiry = expiry
|
|
||||||
|
|
||||||
def set(self, key, value):
|
|
||||||
"""
|
|
||||||
This method is used to set a new value
|
|
||||||
in the memcache server.
|
|
||||||
"""
|
|
||||||
self.server.set(self.normalize_key(key), value, self.expiry)
|
|
||||||
|
|
||||||
def get(self, key):
|
|
||||||
"""
|
|
||||||
This method is used to retrieve a value
|
|
||||||
from the memcache server.
|
|
||||||
"""
|
|
||||||
return self.server.get(self.normalize_key(key))
|
|
||||||
|
|
||||||
def normalize_key(self, key):
|
|
||||||
key = binary_type(key)
|
|
||||||
key = key.replace(' ', '-')
|
|
||||||
return key
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
from __future__ import absolute_import, unicode_literals
|
|
||||||
|
|
||||||
|
|
||||||
class Client(object):
|
|
||||||
cache = None
|
|
||||||
db = None
|
|
||||||
|
|
||||||
def __init__(self, hostname="127.0.0.1", port="11211", expiry=900):
|
|
||||||
if hostname and port:
|
|
||||||
from . import memcache_client
|
|
||||||
|
|
||||||
self.cache = memcache_client.Client(hostname, port, expiry)
|
|
||||||
|
|
||||||
from . import db_client
|
|
||||||
|
|
||||||
self.db = db_client.Client()
|
|
||||||
|
|
||||||
def set(self, key, value):
|
|
||||||
"""
|
|
||||||
This method is used to set a new value
|
|
||||||
in the memcache server and the db.
|
|
||||||
"""
|
|
||||||
self.db.set(key, value)
|
|
||||||
if self.cache:
|
|
||||||
self.cache.set(key, value)
|
|
||||||
|
|
||||||
def get(self, key):
|
|
||||||
"""
|
|
||||||
This method is used to retrieve a value
|
|
||||||
from the memcache server, if found, else it
|
|
||||||
is fetched from db.
|
|
||||||
"""
|
|
||||||
if self.cache:
|
|
||||||
v = self.cache.get(key)
|
|
||||||
if v is None:
|
|
||||||
v = self.db.get(key)
|
|
||||||
if v is not None:
|
|
||||||
self.cache.set(key, v)
|
|
||||||
else:
|
|
||||||
v = self.db.get(key)
|
|
||||||
return v
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
from __future__ import absolute_import, unicode_literals
|
|
||||||
|
|
||||||
from django.db import models
|
|
||||||
from django.utils.encoding import force_text, python_2_unicode_compatible
|
|
||||||
|
|
||||||
|
|
||||||
@python_2_unicode_compatible
|
|
||||||
class KeyMap(models.Model):
|
|
||||||
key = models.CharField(max_length=40, unique=True)
|
|
||||||
value = models.CharField(max_length=100)
|
|
||||||
accessed_on = models.DateTimeField(auto_now=True)
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return force_text("%s => %s" % (self.key, self.value))
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1,9 +0,0 @@
|
||||||
.error a.select2-choice {
|
|
||||||
border: 1px solid #B94A48;
|
|
||||||
}
|
|
||||||
.select2-container {
|
|
||||||
min-width: 150px;
|
|
||||||
}
|
|
||||||
.select2-container.select2-container-multi {
|
|
||||||
width: 300px;
|
|
||||||
}
|
|
||||||
|
|
@ -1,87 +0,0 @@
|
||||||
.form-control .select2-choice {
|
|
||||||
border: 0;
|
|
||||||
border-radius: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control .select2-choice .select2-arrow {
|
|
||||||
border-radius: 0 2px 2px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control.select2-container {
|
|
||||||
height: auto !important;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control.select2-container.select2-dropdown-open {
|
|
||||||
border-color: #5897FB;
|
|
||||||
border-radius: 3px 3px 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control .select2-container.select2-dropdown-open .select2-choices {
|
|
||||||
border-radius: 3px 3px 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-control.select2-container .select2-choices {
|
|
||||||
border: 0 !important;
|
|
||||||
border-radius: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-group.warning .select2-container .select2-choice,
|
|
||||||
.control-group.warning .select2-container .select2-choices,
|
|
||||||
.control-group.warning .select2-container-active .select2-choice,
|
|
||||||
.control-group.warning .select2-container-active .select2-choices,
|
|
||||||
.control-group.warning .select2-dropdown-open.select2-drop-above .select2-choice,
|
|
||||||
.control-group.warning .select2-dropdown-open.select2-drop-above .select2-choices,
|
|
||||||
.control-group.warning .select2-container-multi.select2-container-active .select2-choices {
|
|
||||||
border: 1px solid #C09853 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-group.warning .select2-container .select2-choice div {
|
|
||||||
border-left: 1px solid #C09853 !important;
|
|
||||||
background: #FCF8E3 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-group.error .select2-container .select2-choice,
|
|
||||||
.control-group.error .select2-container .select2-choices,
|
|
||||||
.control-group.error .select2-container-active .select2-choice,
|
|
||||||
.control-group.error .select2-container-active .select2-choices,
|
|
||||||
.control-group.error .select2-dropdown-open.select2-drop-above .select2-choice,
|
|
||||||
.control-group.error .select2-dropdown-open.select2-drop-above .select2-choices,
|
|
||||||
.control-group.error .select2-container-multi.select2-container-active .select2-choices {
|
|
||||||
border: 1px solid #B94A48 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-group.error .select2-container .select2-choice div {
|
|
||||||
border-left: 1px solid #B94A48 !important;
|
|
||||||
background: #F2DEDE !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-group.info .select2-container .select2-choice,
|
|
||||||
.control-group.info .select2-container .select2-choices,
|
|
||||||
.control-group.info .select2-container-active .select2-choice,
|
|
||||||
.control-group.info .select2-container-active .select2-choices,
|
|
||||||
.control-group.info .select2-dropdown-open.select2-drop-above .select2-choice,
|
|
||||||
.control-group.info .select2-dropdown-open.select2-drop-above .select2-choices,
|
|
||||||
.control-group.info .select2-container-multi.select2-container-active .select2-choices {
|
|
||||||
border: 1px solid #3A87AD !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-group.info .select2-container .select2-choice div {
|
|
||||||
border-left: 1px solid #3A87AD !important;
|
|
||||||
background: #D9EDF7 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-group.success .select2-container .select2-choice,
|
|
||||||
.control-group.success .select2-container .select2-choices,
|
|
||||||
.control-group.success .select2-container-active .select2-choice,
|
|
||||||
.control-group.success .select2-container-active .select2-choices,
|
|
||||||
.control-group.success .select2-dropdown-open.select2-drop-above .select2-choice,
|
|
||||||
.control-group.success .select2-dropdown-open.select2-drop-above .select2-choices,
|
|
||||||
.control-group.success .select2-container-multi.select2-container-active .select2-choices {
|
|
||||||
border: 1px solid #468847 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-group.success .select2-container .select2-choice div {
|
|
||||||
border-left: 1px solid #468847 !important;
|
|
||||||
background: #DFF0D8 !important;
|
|
||||||
}
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
|
Before Width: | Height: | Size: 1.8 KiB |
|
|
@ -1,704 +0,0 @@
|
||||||
/*
|
|
||||||
Version: 3.5.2 Timestamp: Sat Nov 1 14:43:36 EDT 2014
|
|
||||||
*/
|
|
||||||
.select2-container {
|
|
||||||
margin: 0;
|
|
||||||
position: relative;
|
|
||||||
display: inline-block;
|
|
||||||
/* inline-block for ie7 */
|
|
||||||
zoom: 1;
|
|
||||||
*display: inline;
|
|
||||||
vertical-align: middle;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container,
|
|
||||||
.select2-drop,
|
|
||||||
.select2-search,
|
|
||||||
.select2-search input {
|
|
||||||
/*
|
|
||||||
Force border-box so that % widths fit the parent
|
|
||||||
container without overlap because of margin/padding.
|
|
||||||
More Info : http://www.quirksmode.org/css/box.html
|
|
||||||
*/
|
|
||||||
-webkit-box-sizing: border-box; /* webkit */
|
|
||||||
-moz-box-sizing: border-box; /* firefox */
|
|
||||||
box-sizing: border-box; /* css3 */
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container .select2-choice {
|
|
||||||
display: block;
|
|
||||||
height: 26px;
|
|
||||||
padding: 0 0 0 8px;
|
|
||||||
overflow: hidden;
|
|
||||||
position: relative;
|
|
||||||
|
|
||||||
border: 1px solid #aaa;
|
|
||||||
white-space: nowrap;
|
|
||||||
line-height: 26px;
|
|
||||||
color: #444;
|
|
||||||
text-decoration: none;
|
|
||||||
|
|
||||||
border-radius: 4px;
|
|
||||||
|
|
||||||
background-clip: padding-box;
|
|
||||||
|
|
||||||
-webkit-touch-callout: none;
|
|
||||||
-webkit-user-select: none;
|
|
||||||
-moz-user-select: none;
|
|
||||||
-ms-user-select: none;
|
|
||||||
user-select: none;
|
|
||||||
|
|
||||||
background-color: #fff;
|
|
||||||
background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eee), color-stop(0.5, #fff));
|
|
||||||
background-image: -webkit-linear-gradient(center bottom, #eee 0%, #fff 50%);
|
|
||||||
background-image: -moz-linear-gradient(center bottom, #eee 0%, #fff 50%);
|
|
||||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#ffffff', endColorstr = '#eeeeee', GradientType = 0);
|
|
||||||
background-image: linear-gradient(to top, #eee 0%, #fff 50%);
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-container .select2-choice {
|
|
||||||
padding: 0 8px 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container.select2-drop-above .select2-choice {
|
|
||||||
border-bottom-color: #aaa;
|
|
||||||
|
|
||||||
border-radius: 0 0 4px 4px;
|
|
||||||
|
|
||||||
background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eee), color-stop(0.9, #fff));
|
|
||||||
background-image: -webkit-linear-gradient(center bottom, #eee 0%, #fff 90%);
|
|
||||||
background-image: -moz-linear-gradient(center bottom, #eee 0%, #fff 90%);
|
|
||||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eeeeee', GradientType=0);
|
|
||||||
background-image: linear-gradient(to bottom, #eee 0%, #fff 90%);
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container.select2-allowclear .select2-choice .select2-chosen {
|
|
||||||
margin-right: 42px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container .select2-choice > .select2-chosen {
|
|
||||||
margin-right: 26px;
|
|
||||||
display: block;
|
|
||||||
overflow: hidden;
|
|
||||||
|
|
||||||
white-space: nowrap;
|
|
||||||
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
float: none;
|
|
||||||
width: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-container .select2-choice > .select2-chosen {
|
|
||||||
margin-left: 26px;
|
|
||||||
margin-right: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container .select2-choice abbr {
|
|
||||||
display: none;
|
|
||||||
width: 12px;
|
|
||||||
height: 12px;
|
|
||||||
position: absolute;
|
|
||||||
right: 24px;
|
|
||||||
top: 8px;
|
|
||||||
|
|
||||||
font-size: 1px;
|
|
||||||
text-decoration: none;
|
|
||||||
|
|
||||||
border: 0;
|
|
||||||
background: url('select2.png') right top no-repeat;
|
|
||||||
cursor: pointer;
|
|
||||||
outline: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container.select2-allowclear .select2-choice abbr {
|
|
||||||
display: inline-block;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container .select2-choice abbr:hover {
|
|
||||||
background-position: right -11px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-drop-mask {
|
|
||||||
border: 0;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
position: fixed;
|
|
||||||
left: 0;
|
|
||||||
top: 0;
|
|
||||||
min-height: 100%;
|
|
||||||
min-width: 100%;
|
|
||||||
height: auto;
|
|
||||||
width: auto;
|
|
||||||
opacity: 0;
|
|
||||||
z-index: 9998;
|
|
||||||
/* styles required for IE to work */
|
|
||||||
background-color: #fff;
|
|
||||||
filter: alpha(opacity=0);
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-drop {
|
|
||||||
width: 100%;
|
|
||||||
margin-top: -1px;
|
|
||||||
position: absolute;
|
|
||||||
z-index: 9999;
|
|
||||||
top: 100%;
|
|
||||||
|
|
||||||
background: #fff;
|
|
||||||
color: #000;
|
|
||||||
border: 1px solid #aaa;
|
|
||||||
border-top: 0;
|
|
||||||
|
|
||||||
border-radius: 0 0 4px 4px;
|
|
||||||
|
|
||||||
-webkit-box-shadow: 0 4px 5px rgba(0, 0, 0, .15);
|
|
||||||
box-shadow: 0 4px 5px rgba(0, 0, 0, .15);
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-drop.select2-drop-above {
|
|
||||||
margin-top: 1px;
|
|
||||||
border-top: 1px solid #aaa;
|
|
||||||
border-bottom: 0;
|
|
||||||
|
|
||||||
border-radius: 4px 4px 0 0;
|
|
||||||
|
|
||||||
-webkit-box-shadow: 0 -4px 5px rgba(0, 0, 0, .15);
|
|
||||||
box-shadow: 0 -4px 5px rgba(0, 0, 0, .15);
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-drop-active {
|
|
||||||
border: 1px solid #5897fb;
|
|
||||||
border-top: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-drop.select2-drop-above.select2-drop-active {
|
|
||||||
border-top: 1px solid #5897fb;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-drop-auto-width {
|
|
||||||
border-top: 1px solid #aaa;
|
|
||||||
width: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-drop-auto-width .select2-search {
|
|
||||||
padding-top: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container .select2-choice .select2-arrow {
|
|
||||||
display: inline-block;
|
|
||||||
width: 18px;
|
|
||||||
height: 100%;
|
|
||||||
position: absolute;
|
|
||||||
right: 0;
|
|
||||||
top: 0;
|
|
||||||
|
|
||||||
border-left: 1px solid #aaa;
|
|
||||||
border-radius: 0 4px 4px 0;
|
|
||||||
|
|
||||||
background-clip: padding-box;
|
|
||||||
|
|
||||||
background: #ccc;
|
|
||||||
background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #ccc), color-stop(0.6, #eee));
|
|
||||||
background-image: -webkit-linear-gradient(center bottom, #ccc 0%, #eee 60%);
|
|
||||||
background-image: -moz-linear-gradient(center bottom, #ccc 0%, #eee 60%);
|
|
||||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#eeeeee', endColorstr = '#cccccc', GradientType = 0);
|
|
||||||
background-image: linear-gradient(to top, #ccc 0%, #eee 60%);
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-container .select2-choice .select2-arrow {
|
|
||||||
left: 0;
|
|
||||||
right: auto;
|
|
||||||
|
|
||||||
border-left: none;
|
|
||||||
border-right: 1px solid #aaa;
|
|
||||||
border-radius: 4px 0 0 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container .select2-choice .select2-arrow b {
|
|
||||||
display: block;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
background: url('select2.png') no-repeat 0 1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-container .select2-choice .select2-arrow b {
|
|
||||||
background-position: 2px 1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-search {
|
|
||||||
display: inline-block;
|
|
||||||
width: 100%;
|
|
||||||
min-height: 26px;
|
|
||||||
margin: 0;
|
|
||||||
padding-left: 4px;
|
|
||||||
padding-right: 4px;
|
|
||||||
|
|
||||||
position: relative;
|
|
||||||
z-index: 10000;
|
|
||||||
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-search input {
|
|
||||||
width: 100%;
|
|
||||||
height: auto !important;
|
|
||||||
min-height: 26px;
|
|
||||||
padding: 4px 20px 4px 5px;
|
|
||||||
margin: 0;
|
|
||||||
|
|
||||||
outline: 0;
|
|
||||||
font-family: sans-serif;
|
|
||||||
font-size: 1em;
|
|
||||||
|
|
||||||
border: 1px solid #aaa;
|
|
||||||
border-radius: 0;
|
|
||||||
|
|
||||||
-webkit-box-shadow: none;
|
|
||||||
box-shadow: none;
|
|
||||||
|
|
||||||
background: #fff url('select2.png') no-repeat 100% -22px;
|
|
||||||
background: url('select2.png') no-repeat 100% -22px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, #fff), color-stop(0.99, #eee));
|
|
||||||
background: url('select2.png') no-repeat 100% -22px, -webkit-linear-gradient(center bottom, #fff 85%, #eee 99%);
|
|
||||||
background: url('select2.png') no-repeat 100% -22px, -moz-linear-gradient(center bottom, #fff 85%, #eee 99%);
|
|
||||||
background: url('select2.png') no-repeat 100% -22px, linear-gradient(to bottom, #fff 85%, #eee 99%) 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-search input {
|
|
||||||
padding: 4px 5px 4px 20px;
|
|
||||||
|
|
||||||
background: #fff url('select2.png') no-repeat -37px -22px;
|
|
||||||
background: url('select2.png') no-repeat -37px -22px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, #fff), color-stop(0.99, #eee));
|
|
||||||
background: url('select2.png') no-repeat -37px -22px, -webkit-linear-gradient(center bottom, #fff 85%, #eee 99%);
|
|
||||||
background: url('select2.png') no-repeat -37px -22px, -moz-linear-gradient(center bottom, #fff 85%, #eee 99%);
|
|
||||||
background: url('select2.png') no-repeat -37px -22px, linear-gradient(to bottom, #fff 85%, #eee 99%) 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-drop.select2-drop-above .select2-search input {
|
|
||||||
margin-top: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-search input.select2-active {
|
|
||||||
background: #fff url('select2-spinner.gif') no-repeat 100%;
|
|
||||||
background: url('select2-spinner.gif') no-repeat 100%, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, #fff), color-stop(0.99, #eee));
|
|
||||||
background: url('select2-spinner.gif') no-repeat 100%, -webkit-linear-gradient(center bottom, #fff 85%, #eee 99%);
|
|
||||||
background: url('select2-spinner.gif') no-repeat 100%, -moz-linear-gradient(center bottom, #fff 85%, #eee 99%);
|
|
||||||
background: url('select2-spinner.gif') no-repeat 100%, linear-gradient(to bottom, #fff 85%, #eee 99%) 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-active .select2-choice,
|
|
||||||
.select2-container-active .select2-choices {
|
|
||||||
border: 1px solid #5897fb;
|
|
||||||
outline: none;
|
|
||||||
|
|
||||||
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, .3);
|
|
||||||
box-shadow: 0 0 5px rgba(0, 0, 0, .3);
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-dropdown-open .select2-choice {
|
|
||||||
border-bottom-color: transparent;
|
|
||||||
-webkit-box-shadow: 0 1px 0 #fff inset;
|
|
||||||
box-shadow: 0 1px 0 #fff inset;
|
|
||||||
|
|
||||||
border-bottom-left-radius: 0;
|
|
||||||
border-bottom-right-radius: 0;
|
|
||||||
|
|
||||||
background-color: #eee;
|
|
||||||
background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #fff), color-stop(0.5, #eee));
|
|
||||||
background-image: -webkit-linear-gradient(center bottom, #fff 0%, #eee 50%);
|
|
||||||
background-image: -moz-linear-gradient(center bottom, #fff 0%, #eee 50%);
|
|
||||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#ffffff', GradientType=0);
|
|
||||||
background-image: linear-gradient(to top, #fff 0%, #eee 50%);
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-dropdown-open.select2-drop-above .select2-choice,
|
|
||||||
.select2-dropdown-open.select2-drop-above .select2-choices {
|
|
||||||
border: 1px solid #5897fb;
|
|
||||||
border-top-color: transparent;
|
|
||||||
|
|
||||||
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #fff), color-stop(0.5, #eee));
|
|
||||||
background-image: -webkit-linear-gradient(center top, #fff 0%, #eee 50%);
|
|
||||||
background-image: -moz-linear-gradient(center top, #fff 0%, #eee 50%);
|
|
||||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#ffffff', GradientType=0);
|
|
||||||
background-image: linear-gradient(to bottom, #fff 0%, #eee 50%);
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-dropdown-open .select2-choice .select2-arrow {
|
|
||||||
background: transparent;
|
|
||||||
border-left: none;
|
|
||||||
filter: none;
|
|
||||||
}
|
|
||||||
html[dir="rtl"] .select2-dropdown-open .select2-choice .select2-arrow {
|
|
||||||
border-right: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-dropdown-open .select2-choice .select2-arrow b {
|
|
||||||
background-position: -18px 1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-dropdown-open .select2-choice .select2-arrow b {
|
|
||||||
background-position: -16px 1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-hidden-accessible {
|
|
||||||
border: 0;
|
|
||||||
clip: rect(0 0 0 0);
|
|
||||||
height: 1px;
|
|
||||||
margin: -1px;
|
|
||||||
overflow: hidden;
|
|
||||||
padding: 0;
|
|
||||||
position: absolute;
|
|
||||||
width: 1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* results */
|
|
||||||
.select2-results {
|
|
||||||
max-height: 200px;
|
|
||||||
padding: 0 0 0 4px;
|
|
||||||
margin: 4px 4px 4px 0;
|
|
||||||
position: relative;
|
|
||||||
overflow-x: hidden;
|
|
||||||
overflow-y: auto;
|
|
||||||
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-results {
|
|
||||||
padding: 0 4px 0 0;
|
|
||||||
margin: 4px 0 4px 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results ul.select2-result-sub {
|
|
||||||
margin: 0;
|
|
||||||
padding-left: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results li {
|
|
||||||
list-style: none;
|
|
||||||
display: list-item;
|
|
||||||
background-image: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results li.select2-result-with-children > .select2-result-label {
|
|
||||||
font-weight: bold;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results .select2-result-label {
|
|
||||||
padding: 3px 7px 4px;
|
|
||||||
margin: 0;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
min-height: 1em;
|
|
||||||
|
|
||||||
-webkit-touch-callout: none;
|
|
||||||
-webkit-user-select: none;
|
|
||||||
-moz-user-select: none;
|
|
||||||
-ms-user-select: none;
|
|
||||||
user-select: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results-dept-1 .select2-result-label { padding-left: 20px }
|
|
||||||
.select2-results-dept-2 .select2-result-label { padding-left: 40px }
|
|
||||||
.select2-results-dept-3 .select2-result-label { padding-left: 60px }
|
|
||||||
.select2-results-dept-4 .select2-result-label { padding-left: 80px }
|
|
||||||
.select2-results-dept-5 .select2-result-label { padding-left: 100px }
|
|
||||||
.select2-results-dept-6 .select2-result-label { padding-left: 110px }
|
|
||||||
.select2-results-dept-7 .select2-result-label { padding-left: 120px }
|
|
||||||
|
|
||||||
.select2-results .select2-highlighted {
|
|
||||||
background: #3875d7;
|
|
||||||
color: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results li em {
|
|
||||||
background: #feffde;
|
|
||||||
font-style: normal;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results .select2-highlighted em {
|
|
||||||
background: transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results .select2-highlighted ul {
|
|
||||||
background: #fff;
|
|
||||||
color: #000;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results .select2-no-results,
|
|
||||||
.select2-results .select2-searching,
|
|
||||||
.select2-results .select2-ajax-error,
|
|
||||||
.select2-results .select2-selection-limit {
|
|
||||||
background: #f4f4f4;
|
|
||||||
display: list-item;
|
|
||||||
padding-left: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
disabled look for disabled choices in the results dropdown
|
|
||||||
*/
|
|
||||||
.select2-results .select2-disabled.select2-highlighted {
|
|
||||||
color: #666;
|
|
||||||
background: #f4f4f4;
|
|
||||||
display: list-item;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
.select2-results .select2-disabled {
|
|
||||||
background: #f4f4f4;
|
|
||||||
display: list-item;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results .select2-selected {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-more-results.select2-active {
|
|
||||||
background: #f4f4f4 url('select2-spinner.gif') no-repeat 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-results .select2-ajax-error {
|
|
||||||
background: rgba(255, 50, 50, .2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-more-results {
|
|
||||||
background: #f4f4f4;
|
|
||||||
display: list-item;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* disabled styles */
|
|
||||||
|
|
||||||
.select2-container.select2-container-disabled .select2-choice {
|
|
||||||
background-color: #f4f4f4;
|
|
||||||
background-image: none;
|
|
||||||
border: 1px solid #ddd;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container.select2-container-disabled .select2-choice .select2-arrow {
|
|
||||||
background-color: #f4f4f4;
|
|
||||||
background-image: none;
|
|
||||||
border-left: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container.select2-container-disabled .select2-choice abbr {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/* multiselect */
|
|
||||||
|
|
||||||
.select2-container-multi .select2-choices {
|
|
||||||
height: auto !important;
|
|
||||||
height: 1%;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0 5px 0 0;
|
|
||||||
position: relative;
|
|
||||||
|
|
||||||
border: 1px solid #aaa;
|
|
||||||
cursor: text;
|
|
||||||
overflow: hidden;
|
|
||||||
|
|
||||||
background-color: #fff;
|
|
||||||
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(1%, #eee), color-stop(15%, #fff));
|
|
||||||
background-image: -webkit-linear-gradient(top, #eee 1%, #fff 15%);
|
|
||||||
background-image: -moz-linear-gradient(top, #eee 1%, #fff 15%);
|
|
||||||
background-image: linear-gradient(to bottom, #eee 1%, #fff 15%);
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-container-multi .select2-choices {
|
|
||||||
padding: 0 0 0 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-locked {
|
|
||||||
padding: 3px 5px 3px 5px !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi .select2-choices {
|
|
||||||
min-height: 26px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi.select2-container-active .select2-choices {
|
|
||||||
border: 1px solid #5897fb;
|
|
||||||
outline: none;
|
|
||||||
|
|
||||||
-webkit-box-shadow: 0 0 5px rgba(0, 0, 0, .3);
|
|
||||||
box-shadow: 0 0 5px rgba(0, 0, 0, .3);
|
|
||||||
}
|
|
||||||
.select2-container-multi .select2-choices li {
|
|
||||||
float: left;
|
|
||||||
list-style: none;
|
|
||||||
}
|
|
||||||
html[dir="rtl"] .select2-container-multi .select2-choices li
|
|
||||||
{
|
|
||||||
float: right;
|
|
||||||
}
|
|
||||||
.select2-container-multi .select2-choices .select2-search-field {
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi .select2-choices .select2-search-field input {
|
|
||||||
padding: 5px;
|
|
||||||
margin: 1px 0;
|
|
||||||
|
|
||||||
font-family: sans-serif;
|
|
||||||
font-size: 100%;
|
|
||||||
color: #666;
|
|
||||||
outline: 0;
|
|
||||||
border: 0;
|
|
||||||
-webkit-box-shadow: none;
|
|
||||||
box-shadow: none;
|
|
||||||
background: transparent !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi .select2-choices .select2-search-field input.select2-active {
|
|
||||||
background: #fff url('select2-spinner.gif') no-repeat 100% !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-default {
|
|
||||||
color: #999 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi .select2-choices .select2-search-choice {
|
|
||||||
padding: 3px 5px 3px 18px;
|
|
||||||
margin: 3px 0 3px 5px;
|
|
||||||
position: relative;
|
|
||||||
|
|
||||||
line-height: 13px;
|
|
||||||
color: #333;
|
|
||||||
cursor: default;
|
|
||||||
border: 1px solid #aaaaaa;
|
|
||||||
|
|
||||||
border-radius: 3px;
|
|
||||||
|
|
||||||
-webkit-box-shadow: 0 0 2px #fff inset, 0 1px 0 rgba(0, 0, 0, 0.05);
|
|
||||||
box-shadow: 0 0 2px #fff inset, 0 1px 0 rgba(0, 0, 0, 0.05);
|
|
||||||
|
|
||||||
background-clip: padding-box;
|
|
||||||
|
|
||||||
-webkit-touch-callout: none;
|
|
||||||
-webkit-user-select: none;
|
|
||||||
-moz-user-select: none;
|
|
||||||
-ms-user-select: none;
|
|
||||||
user-select: none;
|
|
||||||
|
|
||||||
background-color: #e4e4e4;
|
|
||||||
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#f4f4f4', GradientType=0);
|
|
||||||
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eee));
|
|
||||||
background-image: -webkit-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eee 100%);
|
|
||||||
background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eee 100%);
|
|
||||||
background-image: linear-gradient(to bottom, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eee 100%);
|
|
||||||
}
|
|
||||||
html[dir="rtl"] .select2-container-multi .select2-choices .select2-search-choice
|
|
||||||
{
|
|
||||||
margin: 3px 5px 3px 0;
|
|
||||||
padding: 3px 18px 3px 5px;
|
|
||||||
}
|
|
||||||
.select2-container-multi .select2-choices .select2-search-choice .select2-chosen {
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
.select2-container-multi .select2-choices .select2-search-choice-focus {
|
|
||||||
background: #d4d4d4;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-search-choice-close {
|
|
||||||
display: block;
|
|
||||||
width: 12px;
|
|
||||||
height: 13px;
|
|
||||||
position: absolute;
|
|
||||||
right: 3px;
|
|
||||||
top: 4px;
|
|
||||||
|
|
||||||
font-size: 1px;
|
|
||||||
outline: none;
|
|
||||||
background: url('select2.png') right top no-repeat;
|
|
||||||
}
|
|
||||||
html[dir="rtl"] .select2-search-choice-close {
|
|
||||||
right: auto;
|
|
||||||
left: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi .select2-search-choice-close {
|
|
||||||
left: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
html[dir="rtl"] .select2-container-multi .select2-search-choice-close {
|
|
||||||
left: auto;
|
|
||||||
right: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi .select2-choices .select2-search-choice .select2-search-choice-close:hover {
|
|
||||||
background-position: right -11px;
|
|
||||||
}
|
|
||||||
.select2-container-multi .select2-choices .select2-search-choice-focus .select2-search-choice-close {
|
|
||||||
background-position: right -11px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* disabled styles */
|
|
||||||
.select2-container-multi.select2-container-disabled .select2-choices {
|
|
||||||
background-color: #f4f4f4;
|
|
||||||
background-image: none;
|
|
||||||
border: 1px solid #ddd;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi.select2-container-disabled .select2-choices .select2-search-choice {
|
|
||||||
padding: 3px 5px 3px 5px;
|
|
||||||
border: 1px solid #ddd;
|
|
||||||
background-image: none;
|
|
||||||
background-color: #f4f4f4;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-container-multi.select2-container-disabled .select2-choices .select2-search-choice .select2-search-choice-close { display: none;
|
|
||||||
background: none;
|
|
||||||
}
|
|
||||||
/* end multiselect */
|
|
||||||
|
|
||||||
|
|
||||||
.select2-result-selectable .select2-match,
|
|
||||||
.select2-result-unselectable .select2-match {
|
|
||||||
text-decoration: underline;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-offscreen, .select2-offscreen:focus {
|
|
||||||
clip: rect(0 0 0 0) !important;
|
|
||||||
width: 1px !important;
|
|
||||||
height: 1px !important;
|
|
||||||
border: 0 !important;
|
|
||||||
margin: 0 !important;
|
|
||||||
padding: 0 !important;
|
|
||||||
overflow: hidden !important;
|
|
||||||
position: absolute !important;
|
|
||||||
outline: 0 !important;
|
|
||||||
left: 0px !important;
|
|
||||||
top: 0px !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-display-none {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-measure-scrollbar {
|
|
||||||
position: absolute;
|
|
||||||
top: -10000px;
|
|
||||||
left: -10000px;
|
|
||||||
width: 100px;
|
|
||||||
height: 100px;
|
|
||||||
overflow: scroll;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Retina-ize icons */
|
|
||||||
|
|
||||||
@media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 2dppx) {
|
|
||||||
.select2-search input,
|
|
||||||
.select2-search-choice-close,
|
|
||||||
.select2-container .select2-choice abbr,
|
|
||||||
.select2-container .select2-choice .select2-arrow b {
|
|
||||||
background-image: url('select2x2.png') !important;
|
|
||||||
background-repeat: no-repeat !important;
|
|
||||||
background-size: 60px 40px !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select2-search input {
|
|
||||||
background-position: 100% -21px !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
Before Width: | Height: | Size: 613 B |
Binary file not shown.
|
Before Width: | Height: | Size: 845 B |
69
django_select2/static/django_select2/django_select2.js
Normal file
69
django_select2/static/django_select2/django_select2.js
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
/* 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 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 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)
|
||||||
|
|
||||||
|
$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
|
||||||
|
}
|
||||||
|
|
||||||
|
$(function () {
|
||||||
|
$('.django-select2').djangoSelect2()
|
||||||
|
})
|
||||||
|
|
||||||
|
return $.fn.djangoSelect2
|
||||||
|
}))
|
||||||
|
|
@ -1,253 +0,0 @@
|
||||||
if (!window['django_select2']) {
|
|
||||||
// This JS file can be included multiple times. So, as not to overwrite previous states, we run this only once.
|
|
||||||
|
|
||||||
window.django_select2 = {
|
|
||||||
MULTISEPARATOR: String.fromCharCode(31), // We use this unprintable char as separator,
|
|
||||||
// since this can't be entered by user.
|
|
||||||
get_url_params: function (term, page, context) {
|
|
||||||
var field_id = jQuery(this).data('field_id'),
|
|
||||||
res = {
|
|
||||||
'term': term,
|
|
||||||
'page': page,
|
|
||||||
'context': context
|
|
||||||
};
|
|
||||||
if (field_id) {
|
|
||||||
res['field_id'] = field_id;
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
},
|
|
||||||
process_results: function (data, page, context) {
|
|
||||||
var results;
|
|
||||||
if (data.err && data.err.toLowerCase() === 'nil') {
|
|
||||||
results = {
|
|
||||||
'results': data.results
|
|
||||||
};
|
|
||||||
if (context) {
|
|
||||||
results['context'] = context;
|
|
||||||
}
|
|
||||||
if (data.more === true || data.more === false) {
|
|
||||||
results['more'] = data.more;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
results = {'results':[]};
|
|
||||||
}
|
|
||||||
if (results.results) {
|
|
||||||
jQuery(this).data('results', results.results);
|
|
||||||
} else {
|
|
||||||
jQuery(this).removeData('results');
|
|
||||||
}
|
|
||||||
return results;
|
|
||||||
},
|
|
||||||
onValChange: function () {
|
|
||||||
django_select2.updateText(jQuery(this));
|
|
||||||
},
|
|
||||||
prepareValText: function (vals, txts, isMultiple) {
|
|
||||||
var data = []
|
|
||||||
jQuery(vals).each(function (index) {
|
|
||||||
data.push({id: this, text: txts[index]});
|
|
||||||
});
|
|
||||||
if (isMultiple) {
|
|
||||||
return data;
|
|
||||||
} else {
|
|
||||||
if (data.length > 0) {
|
|
||||||
return data[0];
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
updateText: function ($e) {
|
|
||||||
var val = $e.select2('val'), data = $e.select2('data'), txt = $e.txt(), isMultiple = !!$e.attr('multiple'),
|
|
||||||
diff;
|
|
||||||
|
|
||||||
if (val || val === 0) { // Means value is set. A numerical 0 is also a valid value.
|
|
||||||
if (isMultiple) {
|
|
||||||
if (val.length !== txt.length) {
|
|
||||||
txt = [];
|
|
||||||
jQuery(val).each(function (idx) {
|
|
||||||
var i, value = this, id;
|
|
||||||
|
|
||||||
for (i in data) {
|
|
||||||
id = data [i].id;
|
|
||||||
if (id instanceof String) {
|
|
||||||
id = id.valueOf();
|
|
||||||
}
|
|
||||||
if (id == value) {
|
|
||||||
txt.push(data[i].text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
txt = data.text;
|
|
||||||
}
|
|
||||||
$e.txt(txt);
|
|
||||||
} else {
|
|
||||||
$e.txt('');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
getValText: function ($e) {
|
|
||||||
var val = $e.select2('val'), res = $e.data('results'), txt = $e.txt(), isMultiple = !!$e.attr('multiple'),
|
|
||||||
f, id = $e.attr('id');
|
|
||||||
if (val || val === 0) { // Means value is set. A numerical 0 is also a valid value.
|
|
||||||
|
|
||||||
if (!isMultiple) {
|
|
||||||
val = [val];
|
|
||||||
if (txt || txt === 0) {
|
|
||||||
txt = [txt];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (txt === 0 || (txt && val.length === txt.length)) {
|
|
||||||
return [val, txt];
|
|
||||||
}
|
|
||||||
|
|
||||||
f = $e.data('userGetValText');
|
|
||||||
if (f) {
|
|
||||||
txt = f($e, val, isMultiple);
|
|
||||||
if (txt || txt === 0) {
|
|
||||||
return [val, txt];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (res) {
|
|
||||||
txt = [];
|
|
||||||
jQuery(val).each(function (idx) {
|
|
||||||
var i, value = this;
|
|
||||||
|
|
||||||
for (i in res) {
|
|
||||||
if (res[i].id == value) {
|
|
||||||
val[idx] = res[i].id; // To set it to correct data type.
|
|
||||||
txt.push(res[i].text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if (txt || txt === 0) {
|
|
||||||
return [val, txt];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
onInit: function (e, callback) {
|
|
||||||
e = jQuery(e);
|
|
||||||
var id = e.attr('id'), data = null, val = e.select2('val');
|
|
||||||
|
|
||||||
if (!val && val !== 0) {
|
|
||||||
val = e.data('initVal');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (val || val === 0) {
|
|
||||||
// Value is set so need to get the text.
|
|
||||||
data = django_select2.getValText(e);
|
|
||||||
if (data && data[0]) {
|
|
||||||
data = django_select2.prepareValText(data[0], data[1], !!e.attr('multiple'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!data) {
|
|
||||||
e.val(null); // Nulling out set value so as not to confuse users.
|
|
||||||
}
|
|
||||||
callback(data); // Change for 2.3.x
|
|
||||||
django_select2.updateText(e);
|
|
||||||
},
|
|
||||||
createSearchChoice: function(term, data) {
|
|
||||||
if (!data || jQuery(data).filter(function () {
|
|
||||||
return this.text.localeCompare(term) === 0;
|
|
||||||
}).length === 0) {
|
|
||||||
return {
|
|
||||||
id: term,
|
|
||||||
text: term
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onMultipleHiddenChange: function () {
|
|
||||||
var $e = jQuery(this), valContainer = $e.data('valContainer'), name = $e.data('name'), vals = $e.val();
|
|
||||||
valContainer.empty();
|
|
||||||
if (vals) {
|
|
||||||
vals = vals.split(django_select2.MULTISEPARATOR);
|
|
||||||
jQuery(vals).each(function () {
|
|
||||||
var inp = jQuery('<input type="hidden">').appendTo(valContainer);
|
|
||||||
inp.attr('name', name);
|
|
||||||
inp.val(this);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
initMultipleHidden: function ($e) {
|
|
||||||
var valContainer;
|
|
||||||
|
|
||||||
$e.data('name', $e.attr('name'));
|
|
||||||
$e.attr('name', '');
|
|
||||||
|
|
||||||
valContainer = jQuery('<div>').insertAfter($e).css({'display': 'none'});
|
|
||||||
$e.data('valContainer', valContainer);
|
|
||||||
|
|
||||||
$e.change(django_select2.onMultipleHiddenChange);
|
|
||||||
if ($e.val()) {
|
|
||||||
$e.change();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
convertArrToStr: function (arr) {
|
|
||||||
return arr.join(django_select2.MULTISEPARATOR);
|
|
||||||
},
|
|
||||||
runInContextHelper: function (f, id) {
|
|
||||||
return function () {
|
|
||||||
var args = Array.prototype.slice.call(arguments, 0);
|
|
||||||
return f.apply(jQuery('#' + id).get(0), args);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
logErr: function () {
|
|
||||||
if (console && console.error) {
|
|
||||||
args = Array.prototype.slice.call(arguments);
|
|
||||||
console.error.apply(console, args);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
(function (isDebug) { // Only used for debugging.
|
|
||||||
if (isDebug) {
|
|
||||||
for (var i in django_select2) {
|
|
||||||
var f = django_select2[i];
|
|
||||||
if (typeof(f) == "function") {
|
|
||||||
django_select2[i] = (function (i, f) {
|
|
||||||
return function () {
|
|
||||||
console.log('Function ' + i + ' called for object: ', this);
|
|
||||||
return f.apply(this, arguments);
|
|
||||||
};
|
|
||||||
}(i, f));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}(false));
|
|
||||||
|
|
||||||
(function( $ ){
|
|
||||||
// This sets or gets the text lables for an element. It merely takes care returing array or single
|
|
||||||
// value, based on if element is multiple type.
|
|
||||||
$.fn.txt = function(val) {
|
|
||||||
if (typeof(val) !== 'undefined') {
|
|
||||||
if (val) {
|
|
||||||
if (val instanceof Array) {
|
|
||||||
if (this.attr('multiple')) {
|
|
||||||
val = django_select2.convertArrToStr(val);
|
|
||||||
} else {
|
|
||||||
val = val[0]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.attr('txt', val);
|
|
||||||
} else {
|
|
||||||
this.removeAttr('txt');
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
} else {
|
|
||||||
val = this.attr('txt');
|
|
||||||
if (this.attr('multiple')) {
|
|
||||||
if (val) {
|
|
||||||
val = val.split(django_select2.MULTISEPARATOR);
|
|
||||||
} else {
|
|
||||||
val = [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return val;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
})( jQuery );
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
if(!window.django_select2){window.django_select2={MULTISEPARATOR:String.fromCharCode(31),get_url_params:function(c,e,b){var d=jQuery(this).data("field_id"),a={term:c,page:e,context:b};if(d){a.field_id=d}return a},process_results:function(d,c,b){var a;if(d.err&&d.err.toLowerCase()==="nil"){a={results:d.results};if(b){a.context=b}if(d.more===true||d.more===false){a.more=d.more}}else{a={results:[]}}if(a.results){jQuery(this).data("results",a.results)}else{jQuery(this).removeData("results")}return a},onValChange:function(){django_select2.updateText(jQuery(this))},prepareValText:function(d,a,c){var b=[];jQuery(d).each(function(e){b.push({id:this,text:a[e]})});if(c){return b}else{if(b.length>0){return b[0]}else{return null}}},updateText:function(b){var f=b.select2("val"),d=b.select2("data"),a=b.txt(),c=!!b.attr("multiple"),e;if(f||f===0){if(c){if(f.length!==a.length){a=[];jQuery(f).each(function(g){var h,j=this,k;for(h in d){k=d[h].id;if(k instanceof String){k=k.valueOf()}if(k==j){a.push(d[h].text)}}})}}else{a=d.text}b.txt(a)}else{b.txt("")}},getValText:function(b){var g=b.select2("val"),c=b.data("results"),a=b.txt(),e=!!b.attr("multiple"),d,h=b.attr("id");if(g||g===0){if(!e){g=[g];if(a||a===0){a=[a]}}if(a===0||(a&&g.length===a.length)){return[g,a]}d=b.data("userGetValText");if(d){a=d(b,g,e);if(a||a===0){return[g,a]}}if(c){a=[];jQuery(g).each(function(f){var j,k=this;for(j in c){if(c[j].id==k){g[f]=c[j].id;a.push(c[j].text)}}});if(a||a===0){return[g,a]}}}return null},onInit:function(b,f){b=jQuery(b);var d=b.attr("id"),a=null,c=b.select2("val");if(!c&&c!==0){c=b.data("initVal")}if(c||c===0){a=django_select2.getValText(b);if(a&&a[0]){a=django_select2.prepareValText(a[0],a[1],!!b.attr("multiple"))}}if(!a){b.val(null)}f(a);django_select2.updateText(b)},createSearchChoice:function(a,b){if(!b||jQuery(b).filter(function(){return this.text.localeCompare(a)===0}).length===0){return{id:a,text:a}}},onMultipleHiddenChange:function(){var b=jQuery(this),d=b.data("valContainer"),a=b.data("name"),c=b.val();d.empty();if(c){c=c.split(django_select2.MULTISEPARATOR);jQuery(c).each(function(){var e=jQuery('<input type="hidden">').appendTo(d);e.attr("name",a);e.val(this)})}},initMultipleHidden:function(a){var b;a.data("name",a.attr("name"));a.attr("name","");b=jQuery("<div>").insertAfter(a).css({display:"none"});a.data("valContainer",b);a.change(django_select2.onMultipleHiddenChange);if(a.val()){a.change()}},convertArrToStr:function(a){return a.join(django_select2.MULTISEPARATOR)},runInContextHelper:function(a,b){return function(){var c=Array.prototype.slice.call(arguments,0);return a.apply(jQuery("#"+b).get(0),c)}},logErr:function(){if(console&&console.error){args=Array.prototype.slice.call(arguments);console.error.apply(console,args)}}};(function(b){if(b){for(var a in django_select2){var c=django_select2[a];if(typeof(c)=="function"){django_select2[a]=(function(d,e){return function(){console.log("Function "+d+" called for object: ",this);return e.apply(this,arguments)}}(a,c))}}}}(false));(function(a){a.fn.txt=function(b){if(typeof(b)!=="undefined"){if(b){if(b instanceof Array){if(this.attr("multiple")){b=django_select2.convertArrToStr(b)}else{b=b[0]}}this.attr("txt",b)}else{this.removeAttr("txt")}return this}else{b=this.attr("txt");if(this.attr("multiple")){if(b){b=b.split(django_select2.MULTISEPARATOR)}else{b=[]}}return b}}})(jQuery)};
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1,37 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
from __future__ import absolute_import, unicode_literals
|
|
||||||
|
|
||||||
from django import template
|
|
||||||
|
|
||||||
from django_select2.media import (get_select2_css_libs,
|
|
||||||
get_select2_heavy_js_libs,
|
|
||||||
get_select2_js_libs)
|
|
||||||
|
|
||||||
register = template.Library()
|
|
||||||
|
|
||||||
|
|
||||||
def link_tag(css_file):
|
|
||||||
return '<link href="{file}" rel="stylesheet">'.format(file=css_file)
|
|
||||||
|
|
||||||
|
|
||||||
def script_tag(script_file):
|
|
||||||
return '<script type="text/javascript" src="{file}"></script>'.format(file=script_file)
|
|
||||||
|
|
||||||
|
|
||||||
@register.simple_tag(name='import_django_select2_js')
|
|
||||||
def import_js(light=0):
|
|
||||||
if light:
|
|
||||||
js_files = get_select2_js_libs()
|
|
||||||
else:
|
|
||||||
js_files = get_select2_heavy_js_libs()
|
|
||||||
return '\n'.join(script_tag(js_file) for js_file in js_files)
|
|
||||||
|
|
||||||
|
|
||||||
@register.simple_tag(name='import_django_select2_css')
|
|
||||||
def import_css(light=0):
|
|
||||||
return '\n'.join(link_tag(css_file) for css_file in get_select2_css_libs(light=light))
|
|
||||||
|
|
||||||
|
|
||||||
@register.simple_tag(name='import_django_select2_js_css')
|
|
||||||
def import_all(light=0):
|
|
||||||
return import_css(light=light) + import_js(light=light)
|
|
||||||
|
|
@ -1,12 +1,20 @@
|
||||||
# -*- coding:utf-8 -*-
|
"""
|
||||||
from __future__ import absolute_import, unicode_literals
|
Django-Select2 URL configuration.
|
||||||
|
|
||||||
from django.conf.urls import patterns, url
|
Add `django_select` to your ``urlconf`` **if** you use any 'Model' fields::
|
||||||
|
|
||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
|
||||||
|
path('select2/', include('django_select2.urls')),
|
||||||
|
|
||||||
|
"""
|
||||||
|
from django.urls import path
|
||||||
|
|
||||||
from .views import AutoResponseView
|
from .views import AutoResponseView
|
||||||
|
|
||||||
urlpatterns = patterns(
|
app_name = 'django_select2'
|
||||||
"",
|
|
||||||
url(r"^fields/auto.json$",
|
urlpatterns = [
|
||||||
AutoResponseView.as_view(), name="django_select2_central_json"),
|
path("fields/auto.json", AutoResponseView.as_view(), name="auto-json"),
|
||||||
)
|
]
|
||||||
|
|
|
||||||
|
|
@ -1,156 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
from __future__ import absolute_import, unicode_literals
|
|
||||||
|
|
||||||
import datetime
|
|
||||||
import hashlib
|
|
||||||
import logging
|
|
||||||
import re
|
|
||||||
import threading
|
|
||||||
|
|
||||||
from django.utils.six import binary_type, text_type
|
|
||||||
|
|
||||||
from . import __ENABLE_MULTI_PROCESS_SUPPORT as ENABLE_MULTI_PROCESS_SUPPORT
|
|
||||||
from . import __GENERATE_RANDOM_ID as GENERATE_RANDOM_ID
|
|
||||||
from . import __MEMCACHE_HOST as MEMCACHE_HOST
|
|
||||||
from . import __MEMCACHE_PORT as MEMCACHE_PORT
|
|
||||||
from . import __MEMCACHE_TTL as MEMCACHE_TTL
|
|
||||||
from . import __SECRET_SALT as SECRET_SALT
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def extract_some_key_val(dct, keys):
|
|
||||||
"""
|
|
||||||
Gets a sub-set of a :py:obj:`dict`.
|
|
||||||
|
|
||||||
:param dct: Source dictionary.
|
|
||||||
:type dct: :py:obj:`dict`
|
|
||||||
|
|
||||||
:param keys: List of subset keys, which to extract from ``dct``.
|
|
||||||
:type keys: :py:obj:`list` or any iterable.
|
|
||||||
|
|
||||||
:rtype: :py:obj:`dict`
|
|
||||||
"""
|
|
||||||
edct = {}
|
|
||||||
for k in keys:
|
|
||||||
v = dct.get(k, None)
|
|
||||||
if v is not None:
|
|
||||||
edct[k] = v
|
|
||||||
return edct
|
|
||||||
|
|
||||||
|
|
||||||
# ## Auto view helper utils ##
|
|
||||||
|
|
||||||
|
|
||||||
def synchronized(f):
|
|
||||||
"""Decorator to synchronize multiple calls to a functions."""
|
|
||||||
f.__lock__ = threading.Lock()
|
|
||||||
|
|
||||||
def synced_f(*args, **kwargs):
|
|
||||||
with f.__lock__:
|
|
||||||
return f(*args, **kwargs)
|
|
||||||
|
|
||||||
synced_f.__doc__ = f.__doc__
|
|
||||||
return synced_f
|
|
||||||
|
|
||||||
# Generated Id to field instance mapping.
|
|
||||||
__id_store = {}
|
|
||||||
# Field's key to generated Id mapping.
|
|
||||||
__field_store = {}
|
|
||||||
|
|
||||||
ID_PATTERN = r"[0-9_a-zA-Z.:+\- ]+"
|
|
||||||
|
|
||||||
|
|
||||||
def is_valid_id(val):
|
|
||||||
"""
|
|
||||||
Checks if ``val`` is a valid generated Id.
|
|
||||||
|
|
||||||
:param val: The value to check.
|
|
||||||
:type val: :py:obj:`str`
|
|
||||||
|
|
||||||
:rtype: :py:obj:`bool`
|
|
||||||
"""
|
|
||||||
regex = "^%s$" % ID_PATTERN
|
|
||||||
if re.match(regex, val) is None:
|
|
||||||
return False
|
|
||||||
else:
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
if ENABLE_MULTI_PROCESS_SUPPORT:
|
|
||||||
from .memcache_wrapped_db_client import Client
|
|
||||||
|
|
||||||
remote_server = Client(MEMCACHE_HOST, binary_type(MEMCACHE_PORT), MEMCACHE_TTL)
|
|
||||||
|
|
||||||
|
|
||||||
@synchronized
|
|
||||||
def register_field(key, field):
|
|
||||||
"""
|
|
||||||
Registers an Auto field for use with :py:class:`.views.AutoResponseView`.
|
|
||||||
|
|
||||||
:param key: The key to use while registering this field.
|
|
||||||
:type key: :py:obj:`unicode`
|
|
||||||
|
|
||||||
:param field: The field to register.
|
|
||||||
:type field: :py:class:`AutoViewFieldMixin`
|
|
||||||
|
|
||||||
:return: The generated Id for this field. If given ``key`` was already registered then the
|
|
||||||
Id generated that time, would be returned.
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
global __id_store, __field_store
|
|
||||||
|
|
||||||
from .fields import AutoViewFieldMixin
|
|
||||||
|
|
||||||
if not isinstance(field, AutoViewFieldMixin):
|
|
||||||
raise ValueError('Field must extend AutoViewFieldMixin')
|
|
||||||
|
|
||||||
if key not in __field_store:
|
|
||||||
# Generating id
|
|
||||||
if GENERATE_RANDOM_ID:
|
|
||||||
id_ = "%d:%s" % (len(__id_store), text_type(datetime.datetime.now()))
|
|
||||||
else:
|
|
||||||
id_ = text_type(hashlib.sha1(":".join((key, SECRET_SALT)).encode('utf-8')).hexdigest())
|
|
||||||
|
|
||||||
__field_store[key] = id_
|
|
||||||
__id_store[id_] = field
|
|
||||||
|
|
||||||
if logger.isEnabledFor(logging.INFO):
|
|
||||||
logger.info("Registering new field: %s; With actual id: %s", key, id_)
|
|
||||||
|
|
||||||
if ENABLE_MULTI_PROCESS_SUPPORT:
|
|
||||||
logger.info(
|
|
||||||
"Multi process support is enabled. Adding id-key mapping to remote server.")
|
|
||||||
remote_server.set(id_, key)
|
|
||||||
else:
|
|
||||||
id_ = __field_store[key]
|
|
||||||
if logger.isEnabledFor(logging.INFO):
|
|
||||||
logger.info("Field already registered: %s; With actual id: %s", key, id_)
|
|
||||||
return id_
|
|
||||||
|
|
||||||
|
|
||||||
def get_field(id_):
|
|
||||||
"""
|
|
||||||
Returns an Auto field instance registered with the given Id.
|
|
||||||
|
|
||||||
:param id_: The generated Id the field is registered with.
|
|
||||||
:type id_: :py:obj:`unicode`
|
|
||||||
|
|
||||||
:rtype: :py:class:`AutoViewFieldMixin` or None
|
|
||||||
"""
|
|
||||||
field = __id_store.get(id_, None)
|
|
||||||
if field is None and ENABLE_MULTI_PROCESS_SUPPORT:
|
|
||||||
if logger.isEnabledFor(logging.DEBUG):
|
|
||||||
logger.debug('Id "%s" not found in this process. Looking up in remote server.', id_)
|
|
||||||
key = remote_server.get(id_)
|
|
||||||
if key is not None:
|
|
||||||
id_in_current_instance = __field_store[key]
|
|
||||||
if id_in_current_instance:
|
|
||||||
field = __id_store.get(id_in_current_instance, None)
|
|
||||||
if field:
|
|
||||||
__id_store[id_] = field
|
|
||||||
else:
|
|
||||||
logger.error('Unknown id "%s".', id_in_current_instance)
|
|
||||||
else:
|
|
||||||
logger.error('Unknown id "%s".', id_)
|
|
||||||
return field
|
|
||||||
|
|
@ -1,194 +1,92 @@
|
||||||
# -*- 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
|
||||||
|
from django.views.generic.list import BaseListView
|
||||||
|
|
||||||
import json
|
from .cache import cache
|
||||||
|
from .conf import settings
|
||||||
from django.core.exceptions import PermissionDenied
|
|
||||||
from django.http import Http404, HttpResponse
|
|
||||||
from django.utils.six import binary_type
|
|
||||||
from django.views.generic import View
|
|
||||||
|
|
||||||
from .util import get_field, is_valid_id
|
|
||||||
|
|
||||||
NO_ERR_RESP = 'nil'
|
|
||||||
"""
|
|
||||||
Equals to 'nil' constant.
|
|
||||||
|
|
||||||
Use this in :py:meth:`.Select2View.get_results` to mean no error, instead of hardcoding 'nil' value.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
class JSONResponseMixin(object):
|
class AutoResponseView(BaseListView):
|
||||||
"""
|
"""
|
||||||
A mixin that can be used to render a JSON response.
|
View that handles requests from heavy model widgets.
|
||||||
|
|
||||||
|
The view only supports HTTP's GET method.
|
||||||
"""
|
"""
|
||||||
response_class = HttpResponse
|
|
||||||
|
|
||||||
def render_to_response(self, context, **response_kwargs):
|
|
||||||
"""
|
|
||||||
Returns a JSON response, transforming 'context' to make the payload.
|
|
||||||
"""
|
|
||||||
response_kwargs['content_type'] = 'application/json'
|
|
||||||
return self.response_class(
|
|
||||||
self.convert_context_to_json(context),
|
|
||||||
**response_kwargs
|
|
||||||
)
|
|
||||||
|
|
||||||
def convert_context_to_json(self, context):
|
|
||||||
"""Convert the context dictionary into a JSON object"""
|
|
||||||
return json.dumps(context)
|
|
||||||
|
|
||||||
|
|
||||||
class Select2View(JSONResponseMixin, View):
|
|
||||||
"""
|
|
||||||
Base view which is designed to respond with JSON to Ajax queries from heavy widgets/fields.
|
|
||||||
|
|
||||||
Although the widgets won't enforce the type of data_view it gets, but it is recommended to
|
|
||||||
sub-class this view instead of creating a Django view from scratch.
|
|
||||||
|
|
||||||
.. note:: Only `GET <http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3>`_ Http requests are supported.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
|
||||||
try:
|
|
||||||
self.check_all_permissions(request, *args, **kwargs)
|
|
||||||
except Exception as e:
|
|
||||||
return self.respond_with_exception(e)
|
|
||||||
return super(Select2View, self).dispatch(request, *args, **kwargs)
|
|
||||||
|
|
||||||
def get(self, request, *args, **kwargs):
|
def get(self, request, *args, **kwargs):
|
||||||
term = request.GET.get('term', None)
|
|
||||||
if term is None:
|
|
||||||
return self.render_to_response(self._results_to_context(('missing term', False, [], )))
|
|
||||||
|
|
||||||
try:
|
|
||||||
page = int(request.GET.get('page', None))
|
|
||||||
if page <= 0:
|
|
||||||
page = -1
|
|
||||||
except ValueError:
|
|
||||||
page = -1
|
|
||||||
if page == -1:
|
|
||||||
return self.render_to_response(self._results_to_context(('bad page no.', False, [], )))
|
|
||||||
context = request.GET.get('context', None)
|
|
||||||
|
|
||||||
return self.render_to_response(
|
|
||||||
self._results_to_context(
|
|
||||||
self.get_results(request, term, page, context)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
def respond_with_exception(self, e):
|
|
||||||
"""
|
"""
|
||||||
:param e: Exception object.
|
Return a :class:`.django.http.JsonResponse`.
|
||||||
:type e: Exception
|
|
||||||
:return: Response with status code of 404 if e is ``Http404`` object,
|
|
||||||
else 400.
|
|
||||||
:rtype: HttpResponse
|
|
||||||
"""
|
|
||||||
if isinstance(e, Http404):
|
|
||||||
status = 404
|
|
||||||
else:
|
|
||||||
status = getattr(e, 'status_code', 400)
|
|
||||||
return self.render_to_response(
|
|
||||||
self._results_to_context((binary_type(e), False, [],)),
|
|
||||||
status=status
|
|
||||||
)
|
|
||||||
|
|
||||||
def _results_to_context(self, output):
|
Example::
|
||||||
err, has_more, results = output
|
|
||||||
res = []
|
{
|
||||||
if err == NO_ERR_RESP:
|
'results': [
|
||||||
for result in results:
|
{
|
||||||
id_, text = result[:2]
|
'text': "foo",
|
||||||
if len(result) > 2:
|
'id': 123
|
||||||
extra_data = result[2]
|
}
|
||||||
else:
|
],
|
||||||
extra_data = {}
|
'more': true
|
||||||
res.append(dict(id=id_, text=text, **extra_data))
|
|
||||||
return {
|
|
||||||
'err': err,
|
|
||||||
'more': has_more,
|
|
||||||
'results': res,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def check_all_permissions(self, request, *args, **kwargs):
|
|
||||||
"""
|
"""
|
||||||
Sub-classes can use this to raise exception on permission check failures,
|
self.widget = self.get_widget_or_404()
|
||||||
or these checks can be placed in ``urls.py``, e.g. ``login_required(SelectClass.as_view())``.
|
self.term = kwargs.get('term', request.GET.get('term', ''))
|
||||||
|
self.object_list = self.get_queryset()
|
||||||
|
context = self.get_context_data()
|
||||||
|
return JsonResponse({
|
||||||
|
'results': [
|
||||||
|
{
|
||||||
|
'text': self.widget.label_from_instance(obj),
|
||||||
|
'id': obj.pk,
|
||||||
|
}
|
||||||
|
for obj in context['object_list']
|
||||||
|
],
|
||||||
|
'more': context['page_obj'].has_next()
|
||||||
|
})
|
||||||
|
|
||||||
:param request: The Ajax request object.
|
def get_queryset(self):
|
||||||
:type request: :py:class:`django.http.HttpRequest`
|
"""Get QuerySet from cached widget."""
|
||||||
|
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)
|
||||||
|
|
||||||
:param args: The ``*args`` passed to :py:meth:`django.views.generic.View.dispatch`.
|
def get_paginate_by(self, queryset):
|
||||||
:param kwargs: The ``**kwargs`` passed to :py:meth:`django.views.generic.View.dispatch`.
|
"""Paginate response by size of widget's `max_results` parameter."""
|
||||||
|
return self.widget.max_results
|
||||||
|
|
||||||
.. warning:: Sub-classes should override this. You really do not want random people making
|
def get_widget_or_404(self):
|
||||||
Http requests to your server, be able to get access to sensitive information.
|
|
||||||
"""
|
"""
|
||||||
pass
|
Get and return widget from cache.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
Http404: If if the widget can not be found or no id is provided.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ModelSelect2Mixin: Widget from cache.
|
||||||
|
|
||||||
def get_results(self, request, term, page, context):
|
|
||||||
"""
|
"""
|
||||||
Returns the result for the given search ``term``.
|
field_id = self.kwargs.get('field_id', self.request.GET.get('field_id', None))
|
||||||
|
if not field_id:
|
||||||
:param request: The Ajax request object.
|
raise Http404('No "field_id" provided.')
|
||||||
:type request: :py:class:`django.http.HttpRequest`
|
try:
|
||||||
|
key = signing.loads(field_id)
|
||||||
:param term: The search term.
|
except BadSignature:
|
||||||
:type term: :py:obj:`str`
|
raise Http404('Invalid "field_id".')
|
||||||
|
else:
|
||||||
:param page: The page number. If in your last response you had signalled that there are more results,
|
cache_key = '%s%s' % (settings.SELECT2_CACHE_PREFIX, key)
|
||||||
then when user scrolls more a new Ajax request would be sent for the same term but with next page
|
widget_dict = cache.get(cache_key)
|
||||||
number. (Page number starts at 1)
|
if widget_dict is None:
|
||||||
:type page: :py:obj:`int`
|
|
||||||
|
|
||||||
:param context: Can be anything which persists across the lifecycle of queries for the same search term.
|
|
||||||
It is reset to ``None`` when the term changes.
|
|
||||||
|
|
||||||
.. note:: Currently this is not used by ``heavy_data.js``.
|
|
||||||
:type context: :py:obj:`str` or None
|
|
||||||
|
|
||||||
Expected output is of the form::
|
|
||||||
|
|
||||||
(err, has_more, [results])
|
|
||||||
|
|
||||||
Where ``results = [(id1, text1), (id2, text2), ...]``
|
|
||||||
|
|
||||||
For example::
|
|
||||||
|
|
||||||
('nil', False,
|
|
||||||
[
|
|
||||||
(1, 'Value label1'),
|
|
||||||
(20, 'Value label2'),
|
|
||||||
])
|
|
||||||
|
|
||||||
When everything is fine then the `err` must be 'nil'.
|
|
||||||
`has_more` should be true if there are more rows.
|
|
||||||
"""
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
|
|
||||||
class AutoResponseView(Select2View):
|
|
||||||
"""
|
|
||||||
A central view meant to respond to Ajax queries for all Heavy widgets/fields.
|
|
||||||
Although it is not mandatory to use, but is immensely helpful.
|
|
||||||
|
|
||||||
.. tip:: Fields which want to use this view must sub-class :py:class:`~.widgets.AutoViewFieldMixin`.
|
|
||||||
"""
|
|
||||||
def check_all_permissions(self, request, *args, **kwargs):
|
|
||||||
id_ = request.GET.get('field_id', None)
|
|
||||||
if id_ is None or not is_valid_id(id_):
|
|
||||||
raise Http404('field_id not found or is invalid')
|
|
||||||
field = get_field(id_)
|
|
||||||
if field is None:
|
|
||||||
raise Http404('field_id not found')
|
raise Http404('field_id not found')
|
||||||
|
if widget_dict.pop('url') != self.request.path:
|
||||||
if not field.security_check(request, *args, **kwargs):
|
raise Http404('field_id was issued for the view.')
|
||||||
raise PermissionDenied('permission denied')
|
qs, qs.query = widget_dict.pop('queryset')
|
||||||
|
self.queryset = qs.all()
|
||||||
request.__django_select2_local = field
|
widget_dict['queryset'] = self.queryset
|
||||||
|
widget_cls = widget_dict.pop('cls')
|
||||||
def get_results(self, request, term, page, context):
|
return widget_cls(**widget_dict)
|
||||||
field = request.__django_select2_local
|
|
||||||
del request.__django_select2_local
|
|
||||||
return field.get_results(request, term, page, context)
|
|
||||||
|
|
|
||||||
|
|
@ -1,715 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
"""
|
|
||||||
Contains all the Django widgets for Select2.
|
|
||||||
"""
|
|
||||||
from __future__ import absolute_import, unicode_literals
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import re
|
|
||||||
from itertools import chain
|
|
||||||
|
|
||||||
from django import forms
|
|
||||||
from django.core.urlresolvers import reverse
|
|
||||||
from django.core.validators import EMPTY_VALUES
|
|
||||||
from django.utils.datastructures import MergeDict, MultiValueDict
|
|
||||||
from django.utils.encoding import force_text
|
|
||||||
from django.utils.safestring import mark_safe
|
|
||||||
from django.utils.six import text_type
|
|
||||||
|
|
||||||
from django_select2.media import (get_select2_css_libs,
|
|
||||||
get_select2_heavy_js_libs,
|
|
||||||
get_select2_js_libs)
|
|
||||||
|
|
||||||
from . import __RENDER_SELECT2_STATICS as RENDER_SELECT2_STATICS
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
# ## Light mixin and widgets ##
|
|
||||||
|
|
||||||
|
|
||||||
class Select2Mixin(object):
|
|
||||||
"""
|
|
||||||
The base mixin of all Select2 widgets.
|
|
||||||
|
|
||||||
This mixin is responsible for rendering the necessary JavaScript and CSS codes which turns normal ``<select>``
|
|
||||||
markups into Select2 choice list.
|
|
||||||
|
|
||||||
The following Select2 options are added by this mixin:-
|
|
||||||
|
|
||||||
* minimumResultsForSearch: ``6``
|
|
||||||
* placeholder: ``''``
|
|
||||||
* allowClear: ``True``
|
|
||||||
* multiple: ``False``
|
|
||||||
* closeOnSelect: ``False``
|
|
||||||
|
|
||||||
.. note:: Many of them would be removed by sub-classes depending on requirements.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# For details on these options refer: http://ivaynberg.github.com/select2/#documentation
|
|
||||||
options = {
|
|
||||||
'minimumResultsForSearch': 6, # Only applicable for single value select.
|
|
||||||
'placeholder': '', # Empty text label
|
|
||||||
'allowClear': True, # Not allowed when field is multiple since there each value has a clear button.
|
|
||||||
'multiple': False, # Not allowed when attached to <select>
|
|
||||||
'closeOnSelect': False,
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
The options listed here are rendered as JS map and passed to Select2 JS code.
|
|
||||||
Complete description of these options are available in Select2_ JS' site.
|
|
||||||
|
|
||||||
.. _Select2: http://ivaynberg.github.com/select2/#documentation.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
|
||||||
"""
|
|
||||||
Constructor of the class.
|
|
||||||
|
|
||||||
The following additional kwarg is allowed:-
|
|
||||||
|
|
||||||
:param select2_options: This is similar to standard Django way to pass extra attributes to widgets.
|
|
||||||
This is meant to override values of existing :py:attr:`.options`.
|
|
||||||
|
|
||||||
Example::
|
|
||||||
|
|
||||||
class MyForm(ModelForm):
|
|
||||||
class Meta:
|
|
||||||
model = MyModel
|
|
||||||
widgets = {
|
|
||||||
'name': Select2WidgetName(select2_options={
|
|
||||||
'minimumResultsForSearch': 10,
|
|
||||||
'closeOnSelect': True,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
.. tip:: You cannot introduce new options using this. For that you should sub-class and override
|
|
||||||
:py:meth:`.init_options`. The reason for this is, few options are not compatible with each other
|
|
||||||
or are not applicable in some scenarios. For example, when Select2 is attached to a ``<select>`` tag,
|
|
||||||
it can detect if it is being used with a single or multiple values from that tag itself. If you specified the
|
|
||||||
``multiple`` option in this case, it would not only be useless but an error from Select2 JS' point of view.
|
|
||||||
|
|
||||||
There are other such intricacies, based on which some options are removed. By enforcing this
|
|
||||||
restriction we make sure to not break the code by passing some wrong concoction of options.
|
|
||||||
|
|
||||||
.. tip:: According to the select2 documentation, in order to get the ``placeholder`` and ``allowClear``
|
|
||||||
settings working, you have to specify an empty ``<option></option>`` as the first entry in your
|
|
||||||
``<select>`` list. Otherwise the field will be rendered without a placeholder and the clear feature
|
|
||||||
will stay disabled.
|
|
||||||
|
|
||||||
|
|
||||||
:type select2_options: :py:obj:`dict` or None
|
|
||||||
|
|
||||||
"""
|
|
||||||
# Making an instance specific copy
|
|
||||||
self.options = dict(self.options)
|
|
||||||
select2_options = kwargs.pop('select2_options', None)
|
|
||||||
if select2_options:
|
|
||||||
for name, value in select2_options.items():
|
|
||||||
self.options[name] = value
|
|
||||||
self.init_options()
|
|
||||||
|
|
||||||
super(Select2Mixin, self).__init__(**kwargs)
|
|
||||||
|
|
||||||
def init_options(self):
|
|
||||||
"""
|
|
||||||
Sub-classes can use this to suppress or override options passed to Select2 JS library.
|
|
||||||
|
|
||||||
Example::
|
|
||||||
|
|
||||||
def init_options(self):
|
|
||||||
self.options['createSearchChoice'] = 'Your_js_function'
|
|
||||||
|
|
||||||
In the above example we are setting ``Your_js_function`` as Select2's ``createSearchChoice``
|
|
||||||
function.
|
|
||||||
"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
def set_placeholder(self, val):
|
|
||||||
"""
|
|
||||||
Placeholder is a value which Select2 JS library shows when nothing is selected. This should be string.
|
|
||||||
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
self.options['placeholder'] = val
|
|
||||||
|
|
||||||
def get_options(self):
|
|
||||||
"""
|
|
||||||
:return: Dictionary of options to be passed to Select2 JS.
|
|
||||||
|
|
||||||
:rtype: :py:obj:`dict`
|
|
||||||
"""
|
|
||||||
options = dict(self.options)
|
|
||||||
if options.get('allowClear', None) is not None:
|
|
||||||
options['allowClear'] = not self.is_required
|
|
||||||
if options.get('placeholder'):
|
|
||||||
options['placeholder'] = force_text(options['placeholder'])
|
|
||||||
return options
|
|
||||||
|
|
||||||
def render_js_code(self, id_, *args):
|
|
||||||
"""
|
|
||||||
Renders the ``<script>`` block which contains the JS code for this widget.
|
|
||||||
|
|
||||||
:return: The rendered JS code enclosed inside ``<script>`` block.
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
if id_:
|
|
||||||
return self.render_js_script(self.render_inner_js_code(id_, *args))
|
|
||||||
return ''
|
|
||||||
|
|
||||||
def render_js_script(self, inner_code):
|
|
||||||
"""
|
|
||||||
This wraps ``inner_code`` string inside the following code block::
|
|
||||||
|
|
||||||
<script type="text/javascript">
|
|
||||||
jQuery(function ($) {
|
|
||||||
// inner_code here
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
return """
|
|
||||||
<script type="text/javascript">
|
|
||||||
jQuery(function ($) {
|
|
||||||
%s
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
""" % inner_code
|
|
||||||
|
|
||||||
def render_inner_js_code(self, id_, *args):
|
|
||||||
"""
|
|
||||||
Renders all the JS code required for this widget.
|
|
||||||
|
|
||||||
:return: The rendered JS code which will be later enclosed inside ``<script>`` block.
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
options = json.dumps(self.get_options())
|
|
||||||
options = options.replace('"*START*', '').replace('*END*"', '')
|
|
||||||
js = 'var hashedSelector = "#" + "%s";' % id_
|
|
||||||
js += '$(hashedSelector).select2(%s);' % (options)
|
|
||||||
return js
|
|
||||||
|
|
||||||
def render(self, name, value, attrs=None, choices=()):
|
|
||||||
"""
|
|
||||||
Renders this widget. HTML and JS code blocks all are rendered by this.
|
|
||||||
|
|
||||||
:return: The rendered markup.
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
|
|
||||||
args = [name, value, attrs]
|
|
||||||
if choices:
|
|
||||||
args.append(choices)
|
|
||||||
|
|
||||||
s = text_type(super(Select2Mixin, self).render(*args)) # Thanks to @ouhouhsami Issue#1
|
|
||||||
s += self.media.render()
|
|
||||||
final_attrs = self.build_attrs(attrs)
|
|
||||||
id_ = final_attrs.get('id', None)
|
|
||||||
s += self.render_js_code(id_, name, value, attrs, choices)
|
|
||||||
|
|
||||||
return mark_safe(s)
|
|
||||||
|
|
||||||
def _get_media(self):
|
|
||||||
"""
|
|
||||||
Construct Media as a dynamic property
|
|
||||||
|
|
||||||
This is essential because we need to check RENDER_SELECT2_STATICS
|
|
||||||
before returning our assets.
|
|
||||||
|
|
||||||
for more information:
|
|
||||||
https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property
|
|
||||||
"""
|
|
||||||
if RENDER_SELECT2_STATICS:
|
|
||||||
return forms.Media(
|
|
||||||
js=get_select2_js_libs(),
|
|
||||||
css={'screen': get_select2_css_libs(light=True)}
|
|
||||||
)
|
|
||||||
return forms.Media()
|
|
||||||
media = property(_get_media)
|
|
||||||
|
|
||||||
|
|
||||||
class Select2Widget(Select2Mixin, forms.Select):
|
|
||||||
"""
|
|
||||||
Drop-in Select2 replacement for :py:class:`forms.Select`.
|
|
||||||
|
|
||||||
Following Select2 option from :py:attr:`.Select2Mixin.options` is removed:-
|
|
||||||
|
|
||||||
* multiple
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def init_options(self):
|
|
||||||
self.options.pop('multiple', None)
|
|
||||||
|
|
||||||
def render_options(self, choices, selected_choices):
|
|
||||||
all_choices = chain(self.choices, choices)
|
|
||||||
if not self.is_required \
|
|
||||||
and len([value for value, txt in all_choices if value == '']) == 0:
|
|
||||||
# Checking if list already has empty choice
|
|
||||||
# as in the case of Model based Light fields.
|
|
||||||
choices = list(choices)
|
|
||||||
choices.append(('', '', )) # Adding an empty choice
|
|
||||||
return super(Select2Widget, self).render_options(choices, selected_choices)
|
|
||||||
|
|
||||||
|
|
||||||
class Select2MultipleWidget(Select2Mixin, forms.SelectMultiple):
|
|
||||||
"""
|
|
||||||
Drop-in Select2 replacement for :py:class:`forms.SelectMultiple`.
|
|
||||||
|
|
||||||
Following Select2 options from :py:attr:`.Select2Mixin.options` are removed:-
|
|
||||||
|
|
||||||
* multiple
|
|
||||||
* allowClear
|
|
||||||
* minimumResultsForSearch
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def init_options(self):
|
|
||||||
self.options.pop('multiple', None)
|
|
||||||
self.options.pop('allowClear', None)
|
|
||||||
self.options.pop('minimumResultsForSearch', None)
|
|
||||||
|
|
||||||
|
|
||||||
# ## Specialized Multiple Hidden Input Widget ##
|
|
||||||
|
|
||||||
|
|
||||||
class MultipleSelect2HiddenInput(forms.TextInput):
|
|
||||||
"""
|
|
||||||
Multiple hidden input for Select2.
|
|
||||||
|
|
||||||
This is a specialized multiple Hidden Input widget. This includes a special
|
|
||||||
JS component which renders multiple Hidden Input boxes as there are values.
|
|
||||||
So, if user suppose chooses values 1, 4 and 9 then Select2 would would write them
|
|
||||||
to the primary hidden input. The JS component of this widget will read that value and
|
|
||||||
will render three more hidden input boxes each with values 1, 4 and 9 respectively.
|
|
||||||
They will all share the name of this field, and the name of the primary source
|
|
||||||
hidden input would be removed. This way, when submitted all the selected values
|
|
||||||
would be available as list.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def render(self, name, value, attrs=None, choices=()):
|
|
||||||
attrs = self.build_attrs(attrs, multiple='multiple')
|
|
||||||
s = text_type(super(MultipleSelect2HiddenInput, self).render(name, "", attrs))
|
|
||||||
id_ = attrs.get('id', None)
|
|
||||||
if id_:
|
|
||||||
jscode = ''
|
|
||||||
if value:
|
|
||||||
jscode = '$("#%s").val(django_select2.convertArrToStr(%s));' % (id_, json.dumps(value))
|
|
||||||
jscode += "django_select2.initMultipleHidden($('#%s'));" % id_
|
|
||||||
s += self.render_js_script(jscode)
|
|
||||||
return mark_safe(s)
|
|
||||||
|
|
||||||
def value_from_datadict(self, data, files, name):
|
|
||||||
if isinstance(data, (MultiValueDict, MergeDict)):
|
|
||||||
return data.getlist(name)
|
|
||||||
return data.get(name, None)
|
|
||||||
|
|
||||||
def _has_changed(self, initial, data):
|
|
||||||
if initial is None:
|
|
||||||
initial = []
|
|
||||||
if data is None:
|
|
||||||
data = []
|
|
||||||
if len(initial) != len(data):
|
|
||||||
return True
|
|
||||||
initial_set = set([force_text(value) for value in initial])
|
|
||||||
data_set = set([force_text(value) for value in data])
|
|
||||||
return data_set != initial_set
|
|
||||||
|
|
||||||
@property
|
|
||||||
def is_hidden(self):
|
|
||||||
# we return false because even if input_type is 'hidden'
|
|
||||||
# , the final field will be displayed by javascript
|
|
||||||
# and we want label and other layout elements.
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
# ## Heavy mixins and widgets ###
|
|
||||||
|
|
||||||
class HeavySelect2Mixin(Select2Mixin):
|
|
||||||
"""
|
|
||||||
The base mixin of all Heavy Select2 widgets. It sub-classes :py:class:`Select2Mixin`.
|
|
||||||
|
|
||||||
This mixin adds more Select2 options to :py:attr:`.Select2Mixin.options`. These are:-
|
|
||||||
|
|
||||||
* minimumInputLength: ``2``
|
|
||||||
* initSelection: ``'django_select2.onInit'``
|
|
||||||
* ajax:
|
|
||||||
* dataType: ``'json'``
|
|
||||||
* quietMillis: ``100``
|
|
||||||
* data: ``'django_select2.get_url_params'``
|
|
||||||
* results: ``'django_select2.process_results'``
|
|
||||||
|
|
||||||
.. tip:: You can override these options by passing ``select2_options`` kwarg to :py:meth:`.__init__`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
|
||||||
"""
|
|
||||||
Constructor of the class.
|
|
||||||
|
|
||||||
The following kwargs are allowed:-
|
|
||||||
|
|
||||||
:param data_view: A :py:class:`~.views.Select2View` sub-class which can respond to this widget's Ajax queries.
|
|
||||||
:type data_view: :py:class:`django.views.generic.base.View` or None
|
|
||||||
|
|
||||||
:param data_url: Url which will respond to Ajax queries with JSON object.
|
|
||||||
:type data_url: :py:obj:`str` or None
|
|
||||||
|
|
||||||
.. tip:: When ``data_view`` is provided then it is converted into an URL using
|
|
||||||
:py:func:`~django.core.urlresolvers.reverse`.
|
|
||||||
|
|
||||||
.. warning:: Either of ``data_view`` or ``data_url`` must be specified, otherwise :py:exc:`ValueError` will
|
|
||||||
be raised.
|
|
||||||
|
|
||||||
:param choices: The list of available choices. If not provided then empty list is used instead. It
|
|
||||||
should be of the form -- ``[(val1, 'Label1'), (val2, 'Label2'), ...]``.
|
|
||||||
:type choices: :py:obj:`list` or :py:obj:`tuple`
|
|
||||||
|
|
||||||
:param userGetValTextFuncName: The name of the custom JS function which you want to use to convert
|
|
||||||
value to label.
|
|
||||||
|
|
||||||
In ``heavy_data.js``, ``django_select2.getValText()`` employs the following logic to convert value
|
|
||||||
to label :-
|
|
||||||
|
|
||||||
1. First check if the Select2 input field has ``txt`` attribute set along with ``value``. If found
|
|
||||||
then use it.
|
|
||||||
|
|
||||||
2. Otherwise, check if user has provided any custom method for this. Then use that. If it returns a
|
|
||||||
label then use it.
|
|
||||||
|
|
||||||
3. Otherwise, check the cached results. When the user searches in the fields then all the returned
|
|
||||||
responses from server, which has the value and label mapping, are cached by ``heavy_data.js``.
|
|
||||||
|
|
||||||
:type userGetValTextFuncName: :py:obj:`str`
|
|
||||||
|
|
||||||
.. tip:: Since version 3.2.0, cookies or localStorage are no longer checked or used. All
|
|
||||||
:py:class:`~.field.HeavyChoiceField` must override :py:meth:`~.fields.HeavyChoiceField.get_val_txt`.
|
|
||||||
If you are only using heavy widgets in your own fields then you should override :py:meth:`.render_texts`.
|
|
||||||
"""
|
|
||||||
self.field = None
|
|
||||||
self.options = dict(self.options) # Making an instance specific copy
|
|
||||||
self.view = kwargs.pop('data_view', None)
|
|
||||||
self.url = kwargs.pop('data_url', None)
|
|
||||||
self.userGetValTextFuncName = kwargs.pop('userGetValTextFuncName', 'null')
|
|
||||||
self.choices = kwargs.pop('choices', [])
|
|
||||||
|
|
||||||
if not self.view and not self.url:
|
|
||||||
raise ValueError('data_view or data_url is required')
|
|
||||||
|
|
||||||
self.options['ajax'] = {
|
|
||||||
'dataType': 'json',
|
|
||||||
'quietMillis': 100,
|
|
||||||
'data': '*START*django_select2.runInContextHelper(django_select2.get_url_params, selector)*END*',
|
|
||||||
'results': '*START*django_select2.runInContextHelper(django_select2.process_results, selector)*END*',
|
|
||||||
}
|
|
||||||
self.options['minimumInputLength'] = 2
|
|
||||||
self.options['initSelection'] = '*START*django_select2.onInit*END*'
|
|
||||||
super(HeavySelect2Mixin, self).__init__(**kwargs)
|
|
||||||
|
|
||||||
def render_texts(self, selected_choices, choices):
|
|
||||||
"""
|
|
||||||
Renders a JS array with labels for the ``selected_choices``.
|
|
||||||
|
|
||||||
:param selected_choices: List of selected choices' values.
|
|
||||||
:type selected_choices: :py:obj:`list` or :py:obj:`tuple`
|
|
||||||
|
|
||||||
:param choices: Extra choices, if any. This is a list of tuples. In each tuple, the first
|
|
||||||
item is the choice value and the second item is choice label.
|
|
||||||
:type choices: :py:obj:`list` or :py:obj:`tuple`
|
|
||||||
|
|
||||||
:return: The rendered JS array code.
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
selected_choices = list(force_text(v) for v in selected_choices)
|
|
||||||
txts = []
|
|
||||||
all_choices = choices if choices else []
|
|
||||||
choices_dict = dict()
|
|
||||||
self_choices = self.choices
|
|
||||||
|
|
||||||
from . import fields
|
|
||||||
if isinstance(self_choices, fields.FilterableModelChoiceIterator):
|
|
||||||
self_choices.set_extra_filter(**{'%s__in' % self.field.get_pk_field_name(): selected_choices})
|
|
||||||
|
|
||||||
for val, txt in chain(self_choices, all_choices):
|
|
||||||
val = force_text(val)
|
|
||||||
choices_dict[val] = force_text(txt)
|
|
||||||
|
|
||||||
for val in selected_choices:
|
|
||||||
try:
|
|
||||||
txts.append(choices_dict[val])
|
|
||||||
except KeyError:
|
|
||||||
logger.error("Value '%s' is not a valid choice.", val)
|
|
||||||
|
|
||||||
if hasattr(self.field, '_get_val_txt') and selected_choices:
|
|
||||||
for val in selected_choices:
|
|
||||||
txt = self.field._get_val_txt(val)
|
|
||||||
if txt is not None:
|
|
||||||
txts.append(txt)
|
|
||||||
if txts:
|
|
||||||
return json.dumps(txts)
|
|
||||||
|
|
||||||
def get_options(self):
|
|
||||||
if self.url is None:
|
|
||||||
# We lazy resolve the view. By this time Url conf would been loaded fully.
|
|
||||||
self.url = reverse(self.view)
|
|
||||||
|
|
||||||
if self.options['ajax'].get('url', None) is None:
|
|
||||||
self.options['ajax']['url'] = self.url
|
|
||||||
|
|
||||||
return super(HeavySelect2Mixin, self).get_options()
|
|
||||||
|
|
||||||
def render_texts_for_value(self, id_, value, choices):
|
|
||||||
"""
|
|
||||||
Renders the JS code which sets the ``txt`` attribute on the field. It gets the array
|
|
||||||
of lables from :py:meth:`.render_texts`.
|
|
||||||
|
|
||||||
:param id_: Id of the field. This can be used to get reference of this field's DOM in JS.
|
|
||||||
:type id_: :py:obj:`str`
|
|
||||||
|
|
||||||
:param value: Currently set value on the field.
|
|
||||||
:type value: Any
|
|
||||||
|
|
||||||
:param choices: Extra choices, if any. This is a list of tuples. In each tuple, the first
|
|
||||||
item is the choice value and the second item is choice label.
|
|
||||||
:type choices: :py:obj:`list` or :py:obj:`tuple`
|
|
||||||
|
|
||||||
:return: JS code which sets the ``txt`` attribute.
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
empty_values = getattr(self.field, 'empty_values', EMPTY_VALUES)
|
|
||||||
if value is not None and (self.field is None or value not in empty_values):
|
|
||||||
# Just like forms.Select.render() it assumes that value will be single valued.
|
|
||||||
values = [value]
|
|
||||||
texts = self.render_texts(values, choices)
|
|
||||||
if texts:
|
|
||||||
return "$('#%s').txt(%s);" % (id_, texts)
|
|
||||||
|
|
||||||
def render_inner_js_code(self, id_, name, value, attrs=None, choices=(), *args):
|
|
||||||
js = '$(hashedSelector).change(django_select2.onValChange).data("userGetValText", null);'
|
|
||||||
texts = self.render_texts_for_value(id_, value, choices)
|
|
||||||
if texts:
|
|
||||||
js += texts
|
|
||||||
js += super(HeavySelect2Mixin, self).render_inner_js_code(id_, name, value, attrs, choices, *args)
|
|
||||||
return js
|
|
||||||
|
|
||||||
def _get_media(self):
|
|
||||||
"""
|
|
||||||
Construct Media as a dynamic property
|
|
||||||
|
|
||||||
This is essential because we need to check RENDER_SELECT2_STATICS
|
|
||||||
before returning our assets.
|
|
||||||
|
|
||||||
for more information:
|
|
||||||
https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property
|
|
||||||
"""
|
|
||||||
if RENDER_SELECT2_STATICS:
|
|
||||||
return forms.Media(
|
|
||||||
js=get_select2_heavy_js_libs(),
|
|
||||||
css={'screen': get_select2_css_libs()}
|
|
||||||
)
|
|
||||||
return forms.Media()
|
|
||||||
media = property(_get_media)
|
|
||||||
|
|
||||||
|
|
||||||
class HeavySelect2Widget(HeavySelect2Mixin, forms.TextInput):
|
|
||||||
"""
|
|
||||||
Single selection heavy widget.
|
|
||||||
|
|
||||||
Following Select2 option from :py:attr:`.Select2Mixin.options` is added or set:-
|
|
||||||
|
|
||||||
* multiple: ``False``
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def init_options(self):
|
|
||||||
self.options['multiple'] = False
|
|
||||||
|
|
||||||
@property
|
|
||||||
def is_hidden(self):
|
|
||||||
# we return false because even if input_type is 'hidden'
|
|
||||||
# , the final field will be displayed by javascript
|
|
||||||
# and we want label and other layout elements.
|
|
||||||
return False
|
|
||||||
|
|
||||||
def render_inner_js_code(self, id_, *args):
|
|
||||||
field_id = self.field_id if hasattr(self, 'field_id') else id_
|
|
||||||
fieldset_id = re.sub(r'-\d+-', '_', id_).replace('-', '_')
|
|
||||||
if '__prefix__' in id_:
|
|
||||||
return ''
|
|
||||||
else:
|
|
||||||
js = '''
|
|
||||||
window.django_select2.%s = function (selector, fieldID) {
|
|
||||||
var hashedSelector = "#" + selector;
|
|
||||||
$(hashedSelector).data("field_id", fieldID);
|
|
||||||
''' % (fieldset_id)
|
|
||||||
js += super(HeavySelect2Widget, self).render_inner_js_code(id_, *args)
|
|
||||||
js += '};'
|
|
||||||
js += 'django_select2.%s("%s", "%s");' % (fieldset_id, id_, field_id)
|
|
||||||
return js
|
|
||||||
|
|
||||||
|
|
||||||
class HeavySelect2MultipleWidget(HeavySelect2Mixin, MultipleSelect2HiddenInput):
|
|
||||||
"""
|
|
||||||
Multiple selection heavy widget.
|
|
||||||
|
|
||||||
Following Select2 options from :py:attr:`.Select2Mixin.options` are removed:-
|
|
||||||
|
|
||||||
* allowClear
|
|
||||||
* minimumResultsForSearch
|
|
||||||
|
|
||||||
Following Select2 options from :py:attr:`.Select2Mixin.options` are added or set:-
|
|
||||||
|
|
||||||
* multiple: ``True``
|
|
||||||
* separator: ``django_select2.MULTISEPARATOR``
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def init_options(self):
|
|
||||||
self.options['multiple'] = True
|
|
||||||
self.options.pop('allowClear', None)
|
|
||||||
self.options.pop('minimumResultsForSearch', None)
|
|
||||||
self.options['separator'] = '*START*django_select2.MULTISEPARATOR*END*'
|
|
||||||
|
|
||||||
def render_texts_for_value(self, id_, value, choices):
|
|
||||||
"""
|
|
||||||
Renders the JS code which sets the ``txt`` attribute on the field. It gets the array
|
|
||||||
of lables from :py:meth:`.render_texts`.
|
|
||||||
|
|
||||||
:param id_: Id of the field. This can be used to get reference of this field's DOM in JS.
|
|
||||||
:type id_: :py:obj:`str`
|
|
||||||
|
|
||||||
:param value: **List** of currently set value on the field.
|
|
||||||
:type value: :py:obj:`list`
|
|
||||||
|
|
||||||
:param choices: Extra choices, if any. This is a list of tuples. In each tuple, the first
|
|
||||||
item is the choice value and the second item is choice label.
|
|
||||||
:type choices: :py:obj:`list` or :py:obj:`tuple`
|
|
||||||
|
|
||||||
:return: JS code which sets the ``txt`` attribute.
|
|
||||||
:rtype: :py:obj:`unicode`
|
|
||||||
"""
|
|
||||||
# Just like forms.SelectMultiple.render() it assumes that value will be multi-valued (list).
|
|
||||||
if value:
|
|
||||||
texts = self.render_texts(value, choices)
|
|
||||||
if texts:
|
|
||||||
return '$("#%s").txt(%s);' % (id_, texts)
|
|
||||||
|
|
||||||
def render_inner_js_code(self, id_, *args):
|
|
||||||
field_id = self.field_id if hasattr(self, 'field_id') else id_
|
|
||||||
fieldset_id = re.sub(r'-\d+-', '_', id_).replace('-', '_')
|
|
||||||
if '__prefix__' in id_:
|
|
||||||
return ''
|
|
||||||
else:
|
|
||||||
js = '''
|
|
||||||
window.django_select2.%s = function (selector, fieldID) {
|
|
||||||
var hashedSelector = "#" + selector;
|
|
||||||
$(hashedSelector).data("field_id", fieldID);
|
|
||||||
''' % (fieldset_id)
|
|
||||||
js += super(HeavySelect2MultipleWidget, self).render_inner_js_code(id_, *args)
|
|
||||||
js += '};'
|
|
||||||
js += 'django_select2.%s("%s", "%s");' % (fieldset_id, id_, field_id)
|
|
||||||
return js
|
|
||||||
|
|
||||||
|
|
||||||
class HeavySelect2TagWidget(HeavySelect2MultipleWidget):
|
|
||||||
"""
|
|
||||||
Heavy widget with tagging support. Based on :py:class:`HeavySelect2MultipleWidget`,
|
|
||||||
unlike other widgets this allows users to create new options (tags).
|
|
||||||
|
|
||||||
Following Select2 options from :py:attr:`.Select2Mixin.options` are removed:-
|
|
||||||
|
|
||||||
* allowClear
|
|
||||||
* minimumResultsForSearch
|
|
||||||
* closeOnSelect
|
|
||||||
|
|
||||||
Following Select2 options from :py:attr:`.Select2Mixin.options` are added or set:-
|
|
||||||
|
|
||||||
* multiple: ``True``
|
|
||||||
* separator: ``django_select2.MULTISEPARATOR``
|
|
||||||
* tags: ``True``
|
|
||||||
* tokenSeparators: ``,`` and `` ``
|
|
||||||
* createSearchChoice: ``django_select2.createSearchChoice``
|
|
||||||
* minimumInputLength: ``1``
|
|
||||||
|
|
||||||
"""
|
|
||||||
def init_options(self):
|
|
||||||
super(HeavySelect2TagWidget, self).init_options()
|
|
||||||
self.options.pop('closeOnSelect', None)
|
|
||||||
self.options['minimumInputLength'] = 1
|
|
||||||
self.options['tags'] = True
|
|
||||||
self.options['tokenSeparators'] = [",", " "]
|
|
||||||
self.options['createSearchChoice'] = '*START*django_select2.createSearchChoice*END*'
|
|
||||||
|
|
||||||
def render_inner_js_code(self, id_, *args):
|
|
||||||
field_id = self.field_id if hasattr(self, 'field_id') else id_
|
|
||||||
fieldset_id = re.sub(r'-\d+-', '_', id_).replace('-', '_')
|
|
||||||
if '__prefix__' in id_:
|
|
||||||
return ''
|
|
||||||
else:
|
|
||||||
js = '''
|
|
||||||
window.django_select2.%s = function (selector, fieldID) {
|
|
||||||
var hashedSelector = "#" + selector;
|
|
||||||
$(hashedSelector).data("field_id", fieldID);
|
|
||||||
''' % (fieldset_id)
|
|
||||||
js += super(HeavySelect2TagWidget, self).render_inner_js_code(id_, *args)
|
|
||||||
js += '};'
|
|
||||||
js += 'django_select2.%s("%s", "%s");' % (fieldset_id, id_, field_id)
|
|
||||||
return js
|
|
||||||
|
|
||||||
|
|
||||||
# ## Auto Heavy widgets ##
|
|
||||||
|
|
||||||
|
|
||||||
class AutoHeavySelect2Mixin(object):
|
|
||||||
"""
|
|
||||||
This mixin is needed for Auto heavy fields.
|
|
||||||
|
|
||||||
This mixin adds extra JS code to notify the field's DOM object of the generated id. The generated id
|
|
||||||
is not the same as the ``id`` attribute of the field's HTML markup. This id is generated by
|
|
||||||
:py:func:`~.util.register_field` when the Auto field is registered. The client side (DOM) sends this
|
|
||||||
id along with the Ajax request, so that the central view can identify which field should be used to
|
|
||||||
serve the request.
|
|
||||||
|
|
||||||
The js call to dynamically add the `django_select2` is as follows::
|
|
||||||
|
|
||||||
django_select2.id_cities('id_cities', django_select2.id_cities_field_id);
|
|
||||||
|
|
||||||
For an inline formset::
|
|
||||||
|
|
||||||
django_select2.id_musician_set_name(
|
|
||||||
'id_musician_set-0-name', django_select2.id_musician_set_name_field_id);
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
kwargs['data_view'] = "django_select2_central_json"
|
|
||||||
super(AutoHeavySelect2Mixin, self).__init__(*args, **kwargs)
|
|
||||||
|
|
||||||
def render_inner_js_code(self, id_, *args):
|
|
||||||
fieldset_id = re.sub(r'-\d+-', '_', id_).replace('-', '_')
|
|
||||||
if '__prefix__' in id_:
|
|
||||||
return ''
|
|
||||||
else:
|
|
||||||
js = '''
|
|
||||||
window.django_select2.%s = function (selector, fieldID) {
|
|
||||||
var hashedSelector = "#" + selector;
|
|
||||||
$(hashedSelector).data("field_id", fieldID);
|
|
||||||
''' % (fieldset_id)
|
|
||||||
js += super(AutoHeavySelect2Mixin, self).render_inner_js_code(id_, *args)
|
|
||||||
js += '};'
|
|
||||||
js += 'django_select2.%s("%s", "%s");' % (fieldset_id, id_, self.field_id)
|
|
||||||
return js
|
|
||||||
|
|
||||||
|
|
||||||
class AutoHeavySelect2Widget(AutoHeavySelect2Mixin, HeavySelect2Widget):
|
|
||||||
"""Auto version of :py:class:`.HeavySelect2Widget`"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class AutoHeavySelect2MultipleWidget(AutoHeavySelect2Mixin, HeavySelect2MultipleWidget):
|
|
||||||
"""Auto version of :py:class:`.HeavySelect2MultipleWidget`"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class AutoHeavySelect2TagWidget(AutoHeavySelect2Mixin, HeavySelect2TagWidget):
|
|
||||||
"""Auto version of :py:class:`.HeavySelect2TagWidget`"""
|
|
||||||
pass
|
|
||||||
1
docs/CONTRIBUTING.rst
Normal file
1
docs/CONTRIBUTING.rst
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
.. include:: ../CONTRIBUTING.rst
|
||||||
153
docs/Makefile
153
docs/Makefile
|
|
@ -1,153 +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."
|
|
||||||
|
|
||||||
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."
|
|
||||||
287
docs/conf.py
287
docs/conf.py
|
|
@ -1,285 +1,52 @@
|
||||||
# -*- coding: utf-8 -*-
|
import os
|
||||||
#
|
import sys
|
||||||
# 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 sys, os
|
from pkg_resources import get_distribution
|
||||||
|
|
||||||
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
|
|
||||||
|
|
||||||
# This is needed since django_select2 requires django model modules
|
# This is needed since django_select2 requires django model modules
|
||||||
# and those modules assume that django settings is configured and
|
# and those modules assume that django settings is configured and
|
||||||
# have proper DB settings.
|
# have proper DB settings.
|
||||||
# Using this we give a proper environment with working django settings.
|
# Using this we give a proper environment with working django settings.
|
||||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testapp.settings")
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.testapp.settings")
|
||||||
|
|
||||||
# If extensions (or modules to document with autodoc) are in another directory,
|
# 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
|
# 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.
|
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||||
sys.path.insert(0, os.path.abspath('../testapp'))
|
sys.path.insert(0, os.path.abspath('../tests.testapp'))
|
||||||
sys.path.insert(0, os.path.abspath('..'))
|
sys.path.insert(0, os.path.abspath('..'))
|
||||||
|
|
||||||
import datetime
|
|
||||||
year = datetime.datetime.now().strftime("%Y")
|
|
||||||
|
|
||||||
# -- General configuration -----------------------------------------------------
|
project = "Django-Select2"
|
||||||
|
author = "Johannes Hoppe"
|
||||||
|
copyright = "2017, Johannes Hoppe"
|
||||||
|
release = get_distribution('django_select2').version
|
||||||
|
version = '.'.join(release.split('.')[:2])
|
||||||
|
|
||||||
# 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
|
master_doc = 'index' # default in Sphinx v2
|
||||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
|
||||||
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode']
|
|
||||||
|
extensions = [
|
||||||
|
'sphinx.ext.autodoc',
|
||||||
|
'sphinx.ext.napoleon',
|
||||||
|
'sphinx.ext.inheritance_diagram',
|
||||||
|
'sphinx.ext.intersphinx',
|
||||||
|
'sphinx.ext.viewcode',
|
||||||
|
'sphinx.ext.doctest',
|
||||||
|
]
|
||||||
|
|
||||||
intersphinx_mapping = {
|
intersphinx_mapping = {
|
||||||
'python': ('http://docs.python.org/2.7', None),
|
'python': ('http://docs.python.org/3', None),
|
||||||
'django': ('https://docs.djangoproject.com/en/1.4/',
|
'django': ('https://docs.djangoproject.com/en/stable/',
|
||||||
'http://www.applegrew.com/others/django.inv'),
|
'https://docs.djangoproject.com/en/stable/_objects/'),
|
||||||
#'http://docs.djangoproject.com/en/1.4/_objects/'),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# 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_default_flags = ['members', 'show-inheritance']
|
||||||
autodoc_member_order = 'bysource'
|
autodoc_member_order = 'bysource'
|
||||||
|
|
||||||
inheritance_graph_attrs = dict(rankdir="TB", size='""')
|
inheritance_graph_attrs = dict(rankdir='TB')
|
||||||
|
|
||||||
inheritance_node_attrs = dict(shape='ellipse', fontsize=9,
|
inheritance_node_attrs = dict(shape='rect', fontsize=14, fillcolor='gray90',
|
||||||
color='"#97C9FD"', style='filled')
|
color='gray30', style='filled')
|
||||||
|
|
||||||
inheritance_edge_attrs = dict(penwidth=0.75)
|
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 = 'nature'
|
|
||||||
|
|
||||||
# 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'
|
|
||||||
|
|
|
||||||
90
docs/django_select2.rst
Normal file
90
docs/django_select2.rst
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
API Documentation
|
||||||
|
=================
|
||||||
|
|
||||||
|
Configuration
|
||||||
|
-------------
|
||||||
|
|
||||||
|
.. automodule:: django_select2.conf
|
||||||
|
:members:
|
||||||
|
:undoc-members:
|
||||||
|
:show-inheritance:
|
||||||
|
|
||||||
|
Widgets
|
||||||
|
-------
|
||||||
|
|
||||||
|
.. automodule:: django_select2.forms
|
||||||
|
:members:
|
||||||
|
:undoc-members:
|
||||||
|
:show-inheritance:
|
||||||
|
|
||||||
|
URLs
|
||||||
|
----
|
||||||
|
|
||||||
|
.. automodule:: django_select2.urls
|
||||||
|
:members:
|
||||||
|
:undoc-members:
|
||||||
|
:show-inheritance:
|
||||||
|
|
||||||
|
Views
|
||||||
|
-----
|
||||||
|
|
||||||
|
.. automodule:: django_select2.views
|
||||||
|
:members:
|
||||||
|
:undoc-members:
|
||||||
|
:show-inheritance:
|
||||||
|
|
||||||
|
Cache
|
||||||
|
-----
|
||||||
|
|
||||||
|
.. automodule:: django_select2.cache
|
||||||
|
:members:
|
||||||
|
:undoc-members:
|
||||||
|
:show-inheritance:
|
||||||
|
|
||||||
|
|
||||||
|
JavaScript
|
||||||
|
----------
|
||||||
|
|
||||||
|
DjangoSelect2 handles the initialization of select2 fields automatically. Just include
|
||||||
|
``{{ 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, 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();
|
||||||
|
|
||||||
|
|
||||||
|
You can pass see `Select2 options <https://select2.github.io/options.html>`_ if needed::
|
||||||
|
|
||||||
|
$('.django-select2').djangoSelect2({placeholder: 'Select an option'});
|
||||||
|
|
||||||
|
Please replace all your ``.select2`` invocations with the here provided
|
||||||
|
``.djangoSelect2``.
|
||||||
|
|
||||||
|
Security & Authentication
|
||||||
|
-------------------------
|
||||||
|
|
||||||
|
Security is important. Therefore make sure to read and understand what
|
||||||
|
the security measures in place and their limitations.
|
||||||
|
|
||||||
|
Set up a separate cache. If you have a public form that uses a model widget
|
||||||
|
make sure to setup a separate cache database for Select2. An attacker
|
||||||
|
could constantly reload your site and fill up the select2 cache.
|
||||||
|
Having a separate cache allows you to limit the effect to select2 only.
|
||||||
|
|
||||||
|
You might want to add a secure select2 JSON endpoint for data you don't
|
||||||
|
want to be accessible to the general public. Doing so is easy::
|
||||||
|
|
||||||
|
class UserSelect2View(LoginRequiredMixin, AutoResponseView):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class UserSelect2WidgetMixin(object):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
kwargs['data_view'] = 'user-select2-view'
|
||||||
|
super(UserSelect2WidgetMixin, self).__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
class MySecretWidget(UserSelect2WidgetMixin, ModelSelect2Widget):
|
||||||
|
model = MySecretModel
|
||||||
|
search_fields = ['title__icontains']
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
Django >= 1.4.1
|
|
||||||
121
docs/extra.rst
Normal file
121
docs/extra.rst
Normal 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'},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
@ -8,91 +8,71 @@ Overview
|
||||||
.. automodule:: django_select2
|
.. automodule:: django_select2
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
Assumptions
|
||||||
|
-----------
|
||||||
|
|
||||||
|
* You have a running Django up and running.
|
||||||
|
* You have form fully working without Django-Select2.
|
||||||
|
|
||||||
Installation
|
Installation
|
||||||
------------
|
------------
|
||||||
|
|
||||||
1. Install `django_select2`::
|
1. Install ``django_select2``::
|
||||||
|
|
||||||
pip install django_select2
|
pip install django_select2
|
||||||
|
|
||||||
2. Add `django_select2` to your `INSTALLED_APPS` in your project settings.
|
2. Add ``django_select2`` to your ``INSTALLED_APPS`` in your project settings.
|
||||||
|
|
||||||
3. When deploying on production server, run::
|
3. Add ``django_select`` to your ``urlconf``::
|
||||||
|
|
||||||
python manage.py collectstatic
|
path('select2/', include('django_select2.urls')),
|
||||||
|
|
||||||
4. Add `django_select` to your urlconf **if** you use any 'Auto' fields::
|
You can safely skip this one if you do not use any
|
||||||
|
:class:`ModelWidgets <.django_select2.forms.ModelSelect2Mixin>`
|
||||||
|
|
||||||
url(r'^select2/', include('django_select2.urls')),
|
Quick Start
|
||||||
|
-----------
|
||||||
|
|
||||||
5. (Optionally) If you need multiple processes support, then::
|
Here is a quick example to get you started:
|
||||||
|
|
||||||
python manage.py syncdb
|
0. Follow the installation instructions above.
|
||||||
|
|
||||||
Available Settings
|
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::
|
||||||
|
|
||||||
``AUTO_RENDER_SELECT2_STATICS`` [Default ``True``]
|
from django import forms
|
||||||
..................................................
|
from django_select2 import forms as s2forms
|
||||||
|
|
||||||
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`` then every Select2 field on the page will output ``<script>`` and ``<link>`` tags to include the required JS and CSS files. This is convenient but will output the same JS and CSS files multiple times if there are more than one Select2 fields on the page.
|
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::
|
||||||
|
|
||||||
When this settings is ``False`` then you are responsible for including the JS and CSS files. To help you with this the following template tags are available in ``django_select2_tags``.
|
widgets = {
|
||||||
|
'category': s2forms.Select2Widget,
|
||||||
|
'author': s2forms.ModelSelect2Widget(model=auth.get_user_model(),
|
||||||
|
search_fields=['first_name__istartswith', 'last_name__icontains']),
|
||||||
|
'attending': s2forms.ModelSelect2MultipleWidget …
|
||||||
|
}
|
||||||
|
|
||||||
* ``import_django_select2_js`` - Outputs ``<script>`` tags to include all the JS files, required by Light and Heavy widgets.
|
2. Add the CSS to the ``head`` of your Django template::
|
||||||
* ``import_django_select2_css`` - Outputs ``<link>`` tags to include all the CSS files, required by Light and Heavy widgets.
|
|
||||||
* ``import_django_select2_js_css`` - Outputs both ``<script>`` and ``<link>`` tags to include all the JS and CSS files, required by Light and Heavy widgets.
|
|
||||||
|
|
||||||
.. tip:: Make sure to include them at the top of the page, preferably in ``<head>...</head>``.
|
{{ form.media.css }}
|
||||||
|
|
||||||
.. note:: (Since version 3.3.1) The above template tags accept one argument ``light``. Default value for that is ``0``.
|
3. Add the JavaScript to the end of the ``body`` of your Django template::
|
||||||
If that is set to ``1`` then only the JS and CSS libraries needed by Select2Widget (Light fields) are rendered.
|
|
||||||
That effectively leaves out ``heavy.js`` and ``extra.css``.
|
|
||||||
|
|
||||||
``GENERATE_RANDOM_SELECT2_ID`` [Default ``False``]
|
{{ form.media.js }}
|
||||||
..................................................
|
|
||||||
|
|
||||||
As of version 4.0.0 the field's Ids are their paths which have been hashed by SHA1. This Id generation scheme should be sufficient for most applications.
|
4. Done - enjoy the wonders of Select2!
|
||||||
|
|
||||||
However, if you have a secret government project and fear that SHA1 hashes could be cracked (which is not impossible) to reveal the path and names of your fields then you can enable this mode. This will use timestamps as Ids which have no correlation to the field's name or path.
|
|
||||||
|
|
||||||
.. tip:: The field's paths are first salted with Django generated ``SECRET_KEY`` before hashing them.
|
|
||||||
|
|
||||||
``ENABLE_SELECT2_MULTI_PROCESS_SUPPORT`` [Default ``False``]
|
|
||||||
............................................................
|
|
||||||
|
|
||||||
This setting cannot be enabled as it is not required when ``GENERATE_RANDOM_SELECT2_ID`` is ``False``.
|
|
||||||
|
|
||||||
In production servers usually multiple server processes are run to handle the requests. This poses a problem for Django Select2's Auto fields since they generate unique Id at runtime when ``GENERATE_RANDOM_SELECT2_ID`` is enabled. The clients can identify the fields in Ajax query request using only these generated ids. In multi-processes scenario there is no guarantee that the process which rendered the page is the one which will respond to Ajax queries.
|
|
||||||
|
|
||||||
When this mode is enabled then Django Select2 maintains an id to field key mapping in DB for all processes. Whenever a process does not find an id in its internal map it looks-up in the central DB. From DB it finds the field key. Using the key, the process then looks-up a field instance with that key, since all instances with same key are assumed to be equivalent.
|
|
||||||
|
|
||||||
.. tip:: Make sure to run ``python manage.py syncdb`` to create the ``KeyMap`` table.
|
|
||||||
|
|
||||||
.. warning:: You need to write your own script to periodically purge old data from ``KeyMap`` table. You can take help of ``accessed_on`` column. You need to decide the criteria on which basis you will purge the rows.
|
|
||||||
|
|
||||||
|
|
||||||
``SELECT2_MEMCACHE_HOST`` [Default ``None``], ``SELECT2_MEMCACHE_PORT`` [Default ``None``], ``SELECT2_MEMCACHE_TTL`` [Default ``900``]
|
|
||||||
.......................................................................................................................................
|
|
||||||
|
|
||||||
When ``ENABLE_SELECT2_MULTI_PROCESS_SUPPORT`` is enabled then all processes will hit DB to get the mapping for the ids they are not aware of. For performance reasons it is recommended that you install Memcached and set the above settings appropriately.
|
|
||||||
|
|
||||||
Also note that, when you set the above you need to install ``python-memcached`` library too.
|
|
||||||
|
|
||||||
``SELECT2_BOOTSTRAP`` [Default ``False``]
|
|
||||||
............................................................
|
|
||||||
|
|
||||||
Setting to True will include the CSS for making Select2 fit in with Bootstrap a bit better using the css found here https://github.com/fk/select2-bootstrap-css.
|
|
||||||
|
|
||||||
External Dependencies
|
External Dependencies
|
||||||
---------------------
|
---------------------
|
||||||
|
|
||||||
* Django - This is obvious.
|
* jQuery (version >=2)
|
||||||
* jQuery - This is not included in the package since it is expected that in most scenarios this would already be available. The above template tags also won't output ``<script>`` tag to include this. You need to do this yourself.
|
jQuery is not included in the package since it is expected
|
||||||
* Memcached (python-memcached) - If you plan on running multiple Python processes, which is usually the case in production, then you need to turn on ``ENABLE_SELECT2_MULTI_PROCESS_SUPPORT``. In that mode it is highly recommended that you use Memcached, to minimize DB hits.
|
that in most scenarios jQuery is already loaded.
|
||||||
|
|
||||||
Example Application
|
Example Application
|
||||||
-------------------
|
-------------------
|
||||||
Please see ``testapp`` application. This application is used to manually test the functionalities of this package. This also serves as a good example.
|
Please see ``tests/testapp`` application.
|
||||||
|
This application is used to manually test the functionalities of this package.
|
||||||
You need only Django 1.4 or above to run that. It might run on older versions but that is not tested.
|
This also serves as a good example.
|
||||||
|
|
|
||||||
|
|
@ -9,9 +9,13 @@ All Contents
|
||||||
Contents:
|
Contents:
|
||||||
|
|
||||||
.. toctree::
|
.. toctree::
|
||||||
|
:maxdepth: 2
|
||||||
|
:glob:
|
||||||
|
|
||||||
get_started
|
get_started
|
||||||
reference
|
django_select2
|
||||||
|
extra
|
||||||
|
CONTRIBUTING
|
||||||
|
|
||||||
Indices and tables
|
Indices and tables
|
||||||
==================
|
==================
|
||||||
|
|
|
||||||
190
docs/make.bat
190
docs/make.bat
|
|
@ -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
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
Fields
|
|
||||||
======
|
|
||||||
|
|
||||||
Class Diagrams
|
|
||||||
--------------
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.fields.Select2ChoiceField django_select2.fields.Select2MultipleChoiceField
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.fields.ModelSelect2Field django_select2.fields.ModelSelect2MultipleField
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.fields.HeavySelect2TagField
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.fields.HeavyModelSelect2ChoiceField django_select2.fields.HeavyModelSelect2MultipleChoiceField django_select2.fields.HeavyModelSelect2TagField
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.fields.AutoSelect2Field django_select2.fields.AutoSelect2MultipleField django_select2.fields.AutoSelect2TagField
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.fields.AutoModelSelect2Field
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.fields.AutoModelSelect2MultipleField django_select2.fields.AutoModelSelect2TagField
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
Reference
|
|
||||||
---------
|
|
||||||
|
|
||||||
.. automodule:: django_select2.fields
|
|
||||||
:members:
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
Util
|
|
||||||
====
|
|
||||||
|
|
||||||
Class Diagram
|
|
||||||
-------------
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.util
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
|
|
||||||
Reference
|
|
||||||
---------
|
|
||||||
|
|
||||||
.. automodule:: django_select2.util
|
|
||||||
:members:
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
Views
|
|
||||||
=====
|
|
||||||
|
|
||||||
Class Diagram
|
|
||||||
-------------
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.views
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
|
|
||||||
Reference
|
|
||||||
---------
|
|
||||||
|
|
||||||
.. automodule:: django_select2.views
|
|
||||||
:members:
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
Widgets
|
|
||||||
=======
|
|
||||||
|
|
||||||
Class Diagram
|
|
||||||
-------------
|
|
||||||
|
|
||||||
.. inheritance-diagram:: django_select2.widgets
|
|
||||||
:parts: 1
|
|
||||||
|
|
||||||
|
|
||||||
Reference
|
|
||||||
---------
|
|
||||||
|
|
||||||
.. automodule:: django_select2.widgets
|
|
||||||
:members:
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
=============
|
|
||||||
API Reference
|
|
||||||
=============
|
|
||||||
|
|
||||||
The API references also include examples and suggestions, where relevant.
|
|
||||||
|
|
||||||
Contents:
|
|
||||||
|
|
||||||
.. toctree::
|
|
||||||
|
|
||||||
ref_widgets
|
|
||||||
ref_fields
|
|
||||||
ref_views
|
|
||||||
ref_util
|
|
||||||
|
|
||||||
18
docs/spelling_wordlist.txt
Normal file
18
docs/spelling_wordlist.txt
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
jQuery
|
||||||
|
Django
|
||||||
|
mixin
|
||||||
|
backend
|
||||||
|
redis
|
||||||
|
memcached
|
||||||
|
AJAX
|
||||||
|
Cloudflare
|
||||||
|
lookup
|
||||||
|
QuerySet
|
||||||
|
pre
|
||||||
|
py
|
||||||
|
lookups
|
||||||
|
functionalities
|
||||||
|
plugin
|
||||||
|
multi
|
||||||
|
Indices
|
||||||
|
clearable
|
||||||
37
package.json
Normal file
37
package.json
Normal 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": "*"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
[pytest]
|
|
||||||
norecursedirs=env testapp docs
|
|
||||||
addopts = --tb=short --pep8 --flakes -rxs
|
|
||||||
pep8maxlinelength=139
|
|
||||||
pep8ignore=
|
|
||||||
runtests.py ALL
|
|
||||||
flakes-ignore=
|
|
||||||
django_select2/__init__.py UnusedImport
|
|
||||||
django_select2/fields.py UnusedImport
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
pytest
|
|
||||||
pytest-pep8
|
|
||||||
pytest-flakes
|
|
||||||
pytest-django
|
|
||||||
selenium
|
|
||||||
model_mommy
|
|
||||||
isort
|
|
||||||
requests
|
|
||||||
3085
runtests.py
3085
runtests.py
File diff suppressed because it is too large
Load diff
12
set_version.py
Executable file
12
set_version.py
Executable 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()
|
||||||
83
setup.cfg
Normal file
83
setup.cfg
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
[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
|
||||||
|
statistics = true
|
||||||
|
show-source = true
|
||||||
|
|
||||||
|
[pydocstyle]
|
||||||
|
add_ignore = D1
|
||||||
|
|
||||||
|
[isort]
|
||||||
|
atomic = true
|
||||||
|
multi_line_output = 5
|
||||||
|
line_length = 79
|
||||||
|
known_first_party = django_select2, tests
|
||||||
|
default_section=THIRDPARTY
|
||||||
|
combine_as_imports = true
|
||||||
109
setup.py
109
setup.py
|
|
@ -1,110 +1,5 @@
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import codecs
|
from setuptools import setup
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
from setuptools import setup, find_packages, Command
|
setup(name='django-select2', use_scm_version=True)
|
||||||
|
|
||||||
|
|
||||||
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"
|
|
||||||
AUTHOR_EMAIL = "admin@applegrew.com"
|
|
||||||
URL = "https://github.com/applegrew/django-select2"
|
|
||||||
VERSION = __import__(PACKAGE).__version__
|
|
||||||
|
|
||||||
|
|
||||||
def getPkgPath():
|
|
||||||
return __import__(PACKAGE).__path__[0] + '/'
|
|
||||||
|
|
||||||
|
|
||||||
def minify(files, outfile, ftype):
|
|
||||||
import requests
|
|
||||||
import io
|
|
||||||
|
|
||||||
content = ''
|
|
||||||
|
|
||||||
for filename in files:
|
|
||||||
with io.open(getPkgPath() + filename, 'r', encoding='utf8') as f:
|
|
||||||
content = content + '\n' + f.read()
|
|
||||||
|
|
||||||
data = {
|
|
||||||
'code': content,
|
|
||||||
'type': ftype,
|
|
||||||
}
|
|
||||||
response = requests.post('http://api.applegrew.com/minify', data)
|
|
||||||
response.raise_for_status()
|
|
||||||
response = response.json()
|
|
||||||
if response['success']:
|
|
||||||
with io.open(getPkgPath() + outfile, 'w', encoding='utf8') as f:
|
|
||||||
f.write(response['compiled_code'])
|
|
||||||
else:
|
|
||||||
raise Exception('%(error_code)s: "%(error)s"' % response)
|
|
||||||
|
|
||||||
|
|
||||||
if len(sys.argv) > 1 and 'sdist' == sys.argv[1]:
|
|
||||||
minify(['static/django_select2/js/select2.js'], 'static/django_select2/js/select2.min.js', 'js')
|
|
||||||
minify(['static/django_select2/js/heavy_data.js'], 'static/django_select2/js/heavy_data.min.js', 'js')
|
|
||||||
minify(['static/django_select2/css/select2.css'], 'static/django_select2/css/select2.min.css', 'css')
|
|
||||||
minify(['static/django_select2/css/select2.css', 'static/django_select2/css/extra.css'],
|
|
||||||
'static/django_select2/css/all.min.css', 'css')
|
|
||||||
minify(['static/django_select2/css/select2.css', 'static/django_select2/css/select2-bootstrap.css'],
|
|
||||||
'static/django_select2/css/select2-bootstrapped.min.css', 'css')
|
|
||||||
minify(
|
|
||||||
[
|
|
||||||
'static/django_select2/css/select2.css',
|
|
||||||
'static/django_select2/css/extra.css',
|
|
||||||
'static/django_select2/css/select2-bootstrap.css'
|
|
||||||
], 'static/django_select2/css/all-bootstrapped.min.css', 'css')
|
|
||||||
|
|
||||||
|
|
||||||
class PyTest(Command):
|
|
||||||
user_options = []
|
|
||||||
|
|
||||||
def initialize_options(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def finalize_options(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
import sys
|
|
||||||
import subprocess
|
|
||||||
|
|
||||||
errno = subprocess.call([sys.executable, 'runtests.py'])
|
|
||||||
raise SystemExit(errno)
|
|
||||||
|
|
||||||
|
|
||||||
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",
|
|
||||||
"Framework :: Django",
|
|
||||||
],
|
|
||||||
install_requires=[],
|
|
||||||
zip_safe=False,
|
|
||||||
cmdclass={'test': PyTest},
|
|
||||||
)
|
|
||||||
|
|
|
||||||
BIN
testapp/test.db
BIN
testapp/test.db
Binary file not shown.
|
|
@ -1,191 +0,0 @@
|
||||||
# Django settings for testapp project.
|
|
||||||
|
|
||||||
import os.path
|
|
||||||
import posixpath
|
|
||||||
|
|
||||||
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
|
|
||||||
|
|
||||||
import os, sys
|
|
||||||
|
|
||||||
# Including the great parent so that django_select2 can be found.
|
|
||||||
parent_folder = PROJECT_ROOT
|
|
||||||
parent_folder = parent_folder.split('/')[:-2]
|
|
||||||
parent_folder = '/'.join(parent_folder)
|
|
||||||
if parent_folder not in sys.path:
|
|
||||||
sys.path.insert(0, parent_folder)
|
|
||||||
###
|
|
||||||
|
|
||||||
DEBUG = True
|
|
||||||
TEMPLATE_DEBUG = DEBUG
|
|
||||||
|
|
||||||
ADMINS = (
|
|
||||||
# ('Your Name', 'your_email@example.com'),
|
|
||||||
)
|
|
||||||
|
|
||||||
MANAGERS = ADMINS
|
|
||||||
|
|
||||||
DATABASES = {
|
|
||||||
'default': {
|
|
||||||
'ENGINE': 'django.db.backends.sqlite3',
|
|
||||||
'NAME': 'test.db', # Or path to database file if using sqlite3.
|
|
||||||
'USER': '', # Not used with sqlite3.
|
|
||||||
'PASSWORD': '', # Not used with sqlite3.
|
|
||||||
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
|
|
||||||
'PORT': '', # Set to empty string for default. Not used with sqlite3.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Local time zone for this installation. Choices can be found here:
|
|
||||||
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
|
|
||||||
# although not all choices may be available on all operating systems.
|
|
||||||
# In a Windows environment this must be set to your system time zone.
|
|
||||||
TIME_ZONE = 'UTC'
|
|
||||||
|
|
||||||
# Language code for this installation. All choices can be found here:
|
|
||||||
# http://www.i18nguy.com/unicode/language-identifiers.html
|
|
||||||
LANGUAGE_CODE = 'en-us'
|
|
||||||
|
|
||||||
SITE_ID = 1
|
|
||||||
|
|
||||||
# If you set this to False, Django will make some optimizations so as not
|
|
||||||
# to load the internationalization machinery.
|
|
||||||
USE_I18N = True
|
|
||||||
|
|
||||||
# If you set this to False, Django will not format dates, numbers and
|
|
||||||
# calendars according to the current locale.
|
|
||||||
USE_L10N = True
|
|
||||||
|
|
||||||
# If you set this to False, Django will not use timezone-aware datetimes.
|
|
||||||
USE_TZ = True
|
|
||||||
|
|
||||||
# Absolute filesystem path to the directory that will hold user-uploaded files.
|
|
||||||
# Example: "/home/media/media.lawrence.com/media/"
|
|
||||||
MEDIA_ROOT = os.path.join(PROJECT_ROOT, "site_media", "media")
|
|
||||||
|
|
||||||
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
|
|
||||||
# trailing slash.
|
|
||||||
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
|
|
||||||
MEDIA_URL = "/site_media/media/"
|
|
||||||
|
|
||||||
# Absolute path to the directory static files should be collected to.
|
|
||||||
# Don't put anything in this directory yourself; store your static files
|
|
||||||
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
|
|
||||||
# Example: "/home/media/media.lawrence.com/static/"
|
|
||||||
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")
|
|
||||||
|
|
||||||
# URL prefix for static files.
|
|
||||||
# Example: "http://media.lawrence.com/static/"
|
|
||||||
STATIC_URL = '/site_media/static/'
|
|
||||||
|
|
||||||
# Additional locations of static files
|
|
||||||
STATICFILES_DIRS = (
|
|
||||||
os.path.join(PROJECT_ROOT, "static"),
|
|
||||||
)
|
|
||||||
|
|
||||||
# List of finder classes that know how to find static files in
|
|
||||||
# various locations.
|
|
||||||
STATICFILES_FINDERS = (
|
|
||||||
'django.contrib.staticfiles.finders.FileSystemFinder',
|
|
||||||
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
|
|
||||||
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
|
|
||||||
)
|
|
||||||
|
|
||||||
# Make this unique, and don't share it with anybody.
|
|
||||||
SECRET_KEY = 'ps&l59kx$8%&a1vjcj9sim-k^)g9gca0+a@j7o#_ln$(w%-#+k'
|
|
||||||
|
|
||||||
# List of callables that know how to import templates from various sources.
|
|
||||||
TEMPLATE_LOADERS = (
|
|
||||||
'django.template.loaders.filesystem.Loader',
|
|
||||||
'django.template.loaders.app_directories.Loader',
|
|
||||||
# 'django.template.loaders.eggs.Loader',
|
|
||||||
)
|
|
||||||
|
|
||||||
MIDDLEWARE_CLASSES = (
|
|
||||||
'django.middleware.common.CommonMiddleware',
|
|
||||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
|
||||||
'django.middleware.csrf.CsrfViewMiddleware',
|
|
||||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
|
||||||
'django.contrib.messages.middleware.MessageMiddleware',
|
|
||||||
# Uncomment the next line for simple clickjacking protection:
|
|
||||||
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
|
||||||
)
|
|
||||||
|
|
||||||
ROOT_URLCONF = 'testapp.urls'
|
|
||||||
|
|
||||||
# Python dotted path to the WSGI application used by Django's runserver.
|
|
||||||
WSGI_APPLICATION = 'testapp.wsgi.application'
|
|
||||||
|
|
||||||
TEMPLATE_DIRS = (
|
|
||||||
os.path.join(PROJECT_ROOT, "templates"),
|
|
||||||
)
|
|
||||||
|
|
||||||
INSTALLED_APPS = (
|
|
||||||
'django.contrib.auth',
|
|
||||||
'django.contrib.contenttypes',
|
|
||||||
'django.contrib.sessions',
|
|
||||||
'django.contrib.sites',
|
|
||||||
'django.contrib.messages',
|
|
||||||
'django.contrib.staticfiles',
|
|
||||||
# Uncomment the next line to enable the admin:
|
|
||||||
'django.contrib.admin',
|
|
||||||
# Uncomment the next line to enable admin documentation:
|
|
||||||
# 'django.contrib.admindocs',
|
|
||||||
'django_select2',
|
|
||||||
'testapp.testmain',
|
|
||||||
)
|
|
||||||
|
|
||||||
# A sample logging configuration. The only tangible logging
|
|
||||||
# performed by this configuration is to send an email to
|
|
||||||
# the site admins on every HTTP 500 error when DEBUG=False.
|
|
||||||
# See http://docs.djangoproject.com/en/dev/topics/logging for
|
|
||||||
# more details on how to customize your logging configuration.
|
|
||||||
LOGGING = {
|
|
||||||
'version': 1,
|
|
||||||
'disable_existing_loggers': False,
|
|
||||||
'filters': {
|
|
||||||
'require_debug_false': {
|
|
||||||
'()': 'django.utils.log.RequireDebugFalse'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
'handlers': {
|
|
||||||
'mail_admins': {
|
|
||||||
'level': 'ERROR',
|
|
||||||
'filters': ['require_debug_false'],
|
|
||||||
'class': 'django.utils.log.AdminEmailHandler'
|
|
||||||
},
|
|
||||||
'console':{
|
|
||||||
'level':'DEBUG',
|
|
||||||
'class':'logging.StreamHandler'
|
|
||||||
},
|
|
||||||
},
|
|
||||||
'loggers': {
|
|
||||||
'django_select2': {
|
|
||||||
'handlers':['console'],
|
|
||||||
'propagate': True,
|
|
||||||
'level':'DEBUG',
|
|
||||||
},
|
|
||||||
'django.request': {
|
|
||||||
'handlers': ['mail_admins'],
|
|
||||||
'level': 'ERROR',
|
|
||||||
'propagate': True,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AUTO_RENDER_SELECT2_STATICS = False
|
|
||||||
|
|
||||||
#GENERATE_RANDOM_SELECT2_ID = True
|
|
||||||
|
|
||||||
##
|
|
||||||
# To test for multiple processes in development system w/o WSGI, runserver at
|
|
||||||
# different ports. Use $('#select2_field_html_id').data('field_id') to get the id
|
|
||||||
# in one process. Now switch to another port and use
|
|
||||||
# $('#select2_field_html_id').data('field_id', "id from previous process") to set
|
|
||||||
# id from last process. Now try to use that field. Its ajax should still work and
|
|
||||||
# you should see a message like - "Id 7:2013-03-01 14:49:18.490212 not found in
|
|
||||||
# this process. Looking up in remote server.", in console if you have debug enabled.
|
|
||||||
##
|
|
||||||
#ENABLE_SELECT2_MULTI_PROCESS_SUPPORT = True
|
|
||||||
#SELECT2_MEMCACHE_HOST = '127.0.0.1' # Uncomment to use memcached too
|
|
||||||
#SELECT2_MEMCACHE_PORT = 11211 # Uncomment to use memcached too
|
|
||||||
#SELECT2_MEMCACHE_TTL = 9 # Default 900
|
|
||||||
4
testapp/testapp/static/jquery-1.7.2.min.js
vendored
4
testapp/testapp/static/jquery-1.7.2.min.js
vendored
File diff suppressed because one or more lines are too long
|
|
@ -1,7 +0,0 @@
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
Error 500
|
|
||||||
</body>
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
{% load staticfiles %}
|
|
||||||
{% load django_select2_tags %}
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<script src="{{ STATIC_URL }}jquery-1.7.2.min.js"></script>
|
|
||||||
{% import_django_select2_js %}
|
|
||||||
{% import_django_select2_css %}
|
|
||||||
<!-- For testing importing it again, but with another tag and light=1 -->
|
|
||||||
{% import_django_select2_js_css light=1 %}
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<form method="post" action="">
|
|
||||||
{% csrf_token %}
|
|
||||||
<table>
|
|
||||||
{{form}}
|
|
||||||
</table>
|
|
||||||
<input type="submit" value="Submit Form"/>
|
|
||||||
</form>
|
|
||||||
</body>
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
{% load staticfiles %}
|
|
||||||
{% load django_select2_tags %}
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<script src="{{ STATIC_URL }}jquery-1.7.2.min.js"></script>
|
|
||||||
{% import_django_select2_js %}
|
|
||||||
{% import_django_select2_css %}
|
|
||||||
<!-- For testing importing it again, but with another tag and light=1 -->
|
|
||||||
{% import_django_select2_js_css light=1 %}
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<form method="get" action="">
|
|
||||||
<table>
|
|
||||||
{{form}}
|
|
||||||
</table>
|
|
||||||
<input type="submit" value="Submit Form"/>
|
|
||||||
</form>
|
|
||||||
{% for result in results %}
|
|
||||||
<p> {{ result.name}} </p>
|
|
||||||
{% endfor %}
|
|
||||||
</body>
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
{% load url from future %}
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>Manual Tests</h1>
|
|
||||||
<ul>
|
|
||||||
<li><a href="{% url 'test_single_value_model_field' %}">Test single selection model fields</a></li>
|
|
||||||
<li><a href="{% url 'test_multi_values_model_field' %}">Test multi selection model fields</a></li>
|
|
||||||
<li><a href="{% url 'test_mixed_form' %}">Test mixed form. All fields' search must return their own results, not other fields'.</a></li>
|
|
||||||
<li><a href="{% url 'test_init_values' %}">Test that initial values are honored in unbound form</a></li>
|
|
||||||
<li><a href="{% url 'test_list_questions' %}">Test tagging support</a></li>
|
|
||||||
<li><a href="{% url 'test_auto_multivalue_field' %}">Test multi value auto model field.</a></li>
|
|
||||||
<li><a href="{% url 'test_auto_heavy_perf' %}">Test performance. Issue#54.</a></li>
|
|
||||||
<li><a href="{% url 'test_get_search_form' %}">Test a search form using GET. Issue#66.</a></li>
|
|
||||||
<li><a href="{% url 'test_issue_73' %}">Test issue#73.</a></li>
|
|
||||||
</ul>
|
|
||||||
</body>
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
{% load url from future %}
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h2>{{title}}</h2>
|
|
||||||
{% if create_new_href != '' %}
|
|
||||||
<a href="{% url create_new_href %}">Create New</a>
|
|
||||||
<br/>
|
|
||||||
{% endif %}
|
|
||||||
<p>Auto Tags</p>
|
|
||||||
<ul>
|
|
||||||
{% for e in object_list %}
|
|
||||||
<li><a href="{% url href e.id %}">{{ e }}</a></li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
{% if href_non_auto %}
|
|
||||||
<p>Non-Auto Tags</p>
|
|
||||||
<ul>
|
|
||||||
{% for e in object_list %}
|
|
||||||
<li><a href="{% url href_non_auto e.id %}">{{ e }}</a></li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
{% endif %}
|
|
||||||
</body>
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
from django.contrib import admin
|
|
||||||
from .models import ClassRoom, Lab, Dept, Employee, Word, School
|
|
||||||
from .forms import SchoolForm
|
|
||||||
|
|
||||||
|
|
||||||
class SchoolAdmin(admin.ModelAdmin):
|
|
||||||
|
|
||||||
form = SchoolForm
|
|
||||||
|
|
||||||
class Media:
|
|
||||||
js = ['jquery-1.7.2.min.js']
|
|
||||||
|
|
||||||
|
|
||||||
admin.site.register(ClassRoom)
|
|
||||||
admin.site.register(Lab)
|
|
||||||
admin.site.register(Dept)
|
|
||||||
admin.site.register(Employee)
|
|
||||||
admin.site.register(Word)
|
|
||||||
admin.site.register(School, SchoolAdmin)
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
from django_select2 import AutoSelect2MultipleField, AutoModelSelect2MultipleField
|
|
||||||
from django_select2 import NO_ERR_RESP
|
|
||||||
|
|
||||||
from .models import Dept
|
|
||||||
|
|
||||||
class GetSearchTestField(AutoSelect2MultipleField):
|
|
||||||
"""
|
|
||||||
Selects an employee.
|
|
||||||
This field does not render the form value on search results presentation.
|
|
||||||
"""
|
|
||||||
def security_check(self, request, *args, **kwargs):
|
|
||||||
return True
|
|
||||||
def get_results(self, request, term, page, context):
|
|
||||||
"""
|
|
||||||
Just a trivial example, with fixed values.
|
|
||||||
"""
|
|
||||||
res = [('Green Gold','Green Gold'),('Hulk','Hulk'),]
|
|
||||||
return (NO_ERR_RESP, False, res)
|
|
||||||
|
|
||||||
def get_val_txt(self, value):
|
|
||||||
"""
|
|
||||||
The problem of issue #66 was here. I was not overriding this.
|
|
||||||
When using AutoSelect2MultipleField you should implement get_val_txt in this case.
|
|
||||||
I think that this is because there should be an unique correspondence between
|
|
||||||
the referenced value and the shown value
|
|
||||||
In this particular example, the referenced value and the shown value are the same
|
|
||||||
"""
|
|
||||||
return unicode(value)
|
|
||||||
|
|
||||||
class GetModelSearchTestField(AutoModelSelect2MultipleField):
|
|
||||||
"""
|
|
||||||
Selects a department.
|
|
||||||
This field does render the form value on search results presentation. Works OK.
|
|
||||||
"""
|
|
||||||
queryset = Dept.objects.all()
|
|
||||||
search_fields = ['name__icontains']
|
|
||||||
to_field = 'name'
|
|
||||||
|
|
||||||
def security_check(self, request, *args, **kwargs):
|
|
||||||
return True
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,229 +0,0 @@
|
||||||
from django import forms
|
|
||||||
|
|
||||||
from django_select2 import *
|
|
||||||
|
|
||||||
from .models import Employee, Dept, ClassRoom, Lab, Word, School, Tag, Question, WordList
|
|
||||||
|
|
||||||
from .fields import GetSearchTestField, GetModelSearchTestField
|
|
||||||
|
|
||||||
from django.core.exceptions import ValidationError
|
|
||||||
|
|
||||||
|
|
||||||
def validate_fail_always(value):
|
|
||||||
raise ValidationError(u'%s not valid. In fact nothing is valid!' % value)
|
|
||||||
|
|
||||||
|
|
||||||
# Choice fields
|
|
||||||
|
|
||||||
class EmployeeChoices(AutoModelSelect2Field):
|
|
||||||
queryset = Employee.objects
|
|
||||||
search_fields = ['name__icontains', ]
|
|
||||||
|
|
||||||
|
|
||||||
class ClassRoomChoices(AutoModelSelect2MultipleField):
|
|
||||||
queryset = ClassRoom.objects
|
|
||||||
search_fields = ['number__icontains', ]
|
|
||||||
|
|
||||||
|
|
||||||
class ClassRoomSingleChoices(AutoModelSelect2Field):
|
|
||||||
queryset = ClassRoom.objects
|
|
||||||
search_fields = ['number__icontains', ]
|
|
||||||
|
|
||||||
|
|
||||||
class WordChoices(AutoModelSelect2Field):
|
|
||||||
queryset = Word.objects
|
|
||||||
search_fields = ['word__icontains', ]
|
|
||||||
|
|
||||||
|
|
||||||
class MultiWordChoices(AutoModelSelect2MultipleField):
|
|
||||||
queryset = Word.objects
|
|
||||||
search_fields = ['word__icontains', ]
|
|
||||||
|
|
||||||
|
|
||||||
class TagField(AutoModelSelect2TagField):
|
|
||||||
queryset = Tag.objects
|
|
||||||
search_fields = ['tag__icontains', ]
|
|
||||||
|
|
||||||
def get_model_field_values(self, value):
|
|
||||||
return {'tag': value}
|
|
||||||
|
|
||||||
|
|
||||||
class TagNAField(HeavyModelSelect2TagField):
|
|
||||||
def get_model_field_values(self, value):
|
|
||||||
return {'tag': value}
|
|
||||||
|
|
||||||
|
|
||||||
class SelfChoices(AutoSelect2Field):
|
|
||||||
def get_val_txt(self, value):
|
|
||||||
if not hasattr(self, 'res_map'):
|
|
||||||
self.res_map = {}
|
|
||||||
return self.res_map.get(value, None)
|
|
||||||
|
|
||||||
def get_results(self, request, term, page, context):
|
|
||||||
if not hasattr(self, 'res_map'):
|
|
||||||
self.res_map = {}
|
|
||||||
mlen = len(self.res_map)
|
|
||||||
res = []
|
|
||||||
for i in range(1, 6):
|
|
||||||
idx = i + mlen
|
|
||||||
res.append((idx, term * i,))
|
|
||||||
self.res_map[idx] = term * i
|
|
||||||
self.choices = res
|
|
||||||
|
|
||||||
return NO_ERR_RESP, False, res
|
|
||||||
|
|
||||||
|
|
||||||
class SelfMultiChoices(AutoSelect2MultipleField):
|
|
||||||
big_data = {
|
|
||||||
1: u"First", 2: u"Second", 3: u"Third",
|
|
||||||
}
|
|
||||||
|
|
||||||
def validate_value(self, value):
|
|
||||||
if value in [v for v in self.big_data]:
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def coerce_value(self, value):
|
|
||||||
return int(value)
|
|
||||||
|
|
||||||
def get_val_txt(self, value):
|
|
||||||
if not hasattr(self, '_big_data'):
|
|
||||||
self._big_data = dict(self.big_data)
|
|
||||||
return self._big_data.get(value, None)
|
|
||||||
|
|
||||||
def get_results(self, request, term, page, context):
|
|
||||||
if not hasattr(self, '_big_data'):
|
|
||||||
self._big_data = dict(self.big_data)
|
|
||||||
res = [(v, self._big_data[v]) for v in self._big_data]
|
|
||||||
blen = len(res)
|
|
||||||
for i in range(1, 6):
|
|
||||||
idx = i + blen
|
|
||||||
res.append((idx, term * i,))
|
|
||||||
self._big_data[idx] = term * i
|
|
||||||
self.choices = res
|
|
||||||
|
|
||||||
return NO_ERR_RESP, False, res
|
|
||||||
|
|
||||||
|
|
||||||
# Forms
|
|
||||||
|
|
||||||
class SchoolForm(forms.ModelForm):
|
|
||||||
classes = ClassRoomChoices()
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = School
|
|
||||||
fields = ('classes', )
|
|
||||||
|
|
||||||
|
|
||||||
class EmployeeForm(forms.ModelForm):
|
|
||||||
manager = EmployeeChoices(required=False)
|
|
||||||
dept = ModelSelect2Field(queryset=Dept.objects)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = Employee
|
|
||||||
fields = ('name', 'salary', 'dept', 'manager')
|
|
||||||
|
|
||||||
|
|
||||||
class DeptForm(forms.ModelForm):
|
|
||||||
allotted_rooms = ClassRoomChoices()
|
|
||||||
allotted_labs = ModelSelect2MultipleField(queryset=Lab.objects, required=False)
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = Dept
|
|
||||||
fields = ('name', 'allotted_rooms', 'allotted_labs')
|
|
||||||
|
|
||||||
|
|
||||||
class MixedForm(forms.Form):
|
|
||||||
emp1 = EmployeeChoices()
|
|
||||||
rooms1 = ClassRoomChoices()
|
|
||||||
emp2 = EmployeeChoices()
|
|
||||||
rooms2 = ClassRoomChoices()
|
|
||||||
rooms3 = ClassRoomSingleChoices()
|
|
||||||
any_word = WordChoices()
|
|
||||||
self_choices = SelfChoices(label='Self copy choices')
|
|
||||||
self_multi_choices = SelfMultiChoices(label='Self copy multi-choices')
|
|
||||||
issue11_test = EmployeeChoices(
|
|
||||||
label='Issue 11 Test (Employee)',
|
|
||||||
widget=AutoHeavySelect2Widget(
|
|
||||||
select2_options={
|
|
||||||
'width': '32em',
|
|
||||||
'placeholder': u"Search foo"
|
|
||||||
}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
always_fail_rooms = ClassRoomSingleChoices(validators=[validate_fail_always])
|
|
||||||
always_fail_rooms_multi = ClassRoomChoices(validators=[validate_fail_always])
|
|
||||||
always_fail_self_choice = SelfChoices(validators=[validate_fail_always], auto_id='always_fail_self_choice')
|
|
||||||
always_fail_self_choice_multi = SelfMultiChoices(validators=[validate_fail_always],
|
|
||||||
auto_id='always_fail_self_choice_multi')
|
|
||||||
model_with_both_required_and_empty_label_false = ModelSelect2Field(
|
|
||||||
queryset=Employee.objects, empty_label=None, required=False) # issue#26
|
|
||||||
|
|
||||||
# These are just for testing Auto registration of fields
|
|
||||||
EmployeeChoices() # Should already be registered
|
|
||||||
EmployeeChoices(auto_id="EmployeeChoices_CustomAutoId") # Should get registered
|
|
||||||
|
|
||||||
|
|
||||||
class InitialValueForm(forms.Form):
|
|
||||||
select2Choice = Select2ChoiceField(initial=2,
|
|
||||||
choices=((1, "First"), (2, "Second"), (3, "Third"), ))
|
|
||||||
select2MultipleChoice = Select2MultipleChoiceField(initial=[2, 3],
|
|
||||||
choices=((1, "First"), (2, "Second"), (3, "Third"), ))
|
|
||||||
heavySelect2Choice = AutoSelect2Field(initial=2,
|
|
||||||
choices=((1, "First"), (2, "Second"), (3, "Third"), ))
|
|
||||||
heavySelect2MultipleChoice = AutoSelect2MultipleField(initial=[1, 3],
|
|
||||||
choices=((1, "First"), (2, "Second"), (3, "Third"), ))
|
|
||||||
self_choices = SelfChoices(label='Self copy choices', initial=2,
|
|
||||||
choices=((1, "First"), (2, "Second"), (3, "Third"), ))
|
|
||||||
self_multi_choices = SelfMultiChoices(label='Self copy multi-choices', initial=[2, 3])
|
|
||||||
select2ChoiceWithQuotes = Select2ChoiceField(initial=2,
|
|
||||||
choices=((1, "'Single-Quote'"), (2, "\"Double-Quotes\""),
|
|
||||||
(3, "\"Mixed-Quotes'"), ))
|
|
||||||
heavySelect2ChoiceWithQuotes = AutoSelect2Field(initial=2,
|
|
||||||
choices=((1, "'Single-Quote'"), (2, "\"Double-Quotes\""),
|
|
||||||
(3, "\"Mixed-Quotes'"), ))
|
|
||||||
|
|
||||||
|
|
||||||
class QuestionForm(forms.ModelForm):
|
|
||||||
question = forms.CharField()
|
|
||||||
description = forms.CharField(widget=forms.Textarea)
|
|
||||||
tags = TagField()
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = Question
|
|
||||||
fields = ('question', 'description', 'tags')
|
|
||||||
|
|
||||||
|
|
||||||
class QuestionNonAutoForm(forms.ModelForm):
|
|
||||||
question = forms.CharField()
|
|
||||||
description = forms.CharField(widget=forms.Textarea)
|
|
||||||
tags = TagNAField(queryset=Tag.objects,
|
|
||||||
search_fields=['tag__icontains'],
|
|
||||||
widget=HeavySelect2TagWidget(data_view='test_tagging_tags'))
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = Question
|
|
||||||
fields = ('question', 'description', 'tags')
|
|
||||||
|
|
||||||
|
|
||||||
class WordsForm(forms.ModelForm):
|
|
||||||
word = WordChoices()
|
|
||||||
words = MultiWordChoices()
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = WordList
|
|
||||||
exclude = ['kind']
|
|
||||||
|
|
||||||
|
|
||||||
class GetSearchTestForm(forms.Form):
|
|
||||||
name = GetSearchTestField(required=False, label='Name')
|
|
||||||
dept = GetModelSearchTestField(required=False, label='Department')
|
|
||||||
|
|
||||||
|
|
||||||
class AnotherWordForm(forms.ModelForm):
|
|
||||||
word = WordChoices(widget=AutoHeavySelect2Widget())
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
model = WordList
|
|
||||||
exclude = ['kind', 'words']
|
|
||||||
|
|
@ -1,66 +0,0 @@
|
||||||
from django.db import models
|
|
||||||
|
|
||||||
class ClassRoom(models.Model):
|
|
||||||
number = models.CharField(max_length=4)
|
|
||||||
|
|
||||||
def __unicode__(self):
|
|
||||||
return unicode(self.number)
|
|
||||||
|
|
||||||
class Lab(models.Model):
|
|
||||||
name = models.CharField(max_length=10)
|
|
||||||
|
|
||||||
def __unicode__(self):
|
|
||||||
return unicode(self.name)
|
|
||||||
|
|
||||||
class Dept(models.Model):
|
|
||||||
name = models.CharField(max_length=10)
|
|
||||||
allotted_rooms = models.ManyToManyField(ClassRoom)
|
|
||||||
allotted_labs = models.ManyToManyField(Lab)
|
|
||||||
|
|
||||||
def __unicode__(self):
|
|
||||||
return unicode(self.name)
|
|
||||||
|
|
||||||
class Employee(models.Model):
|
|
||||||
name = models.CharField(max_length=30)
|
|
||||||
salary = models.FloatField()
|
|
||||||
dept = models.ForeignKey(Dept)
|
|
||||||
manager = models.ForeignKey('Employee', null=True, blank=True)
|
|
||||||
|
|
||||||
def __unicode__(self):
|
|
||||||
return unicode(self.name)
|
|
||||||
|
|
||||||
class Word(models.Model):
|
|
||||||
word = models.CharField(max_length=15)
|
|
||||||
|
|
||||||
def __unicode__(self):
|
|
||||||
return unicode(self.word)
|
|
||||||
|
|
||||||
|
|
||||||
class School(models.Model):
|
|
||||||
classes = models.ManyToManyField(ClassRoom)
|
|
||||||
|
|
||||||
class Tag(models.Model):
|
|
||||||
tag = models.CharField(max_length=10, unique=True)
|
|
||||||
|
|
||||||
def __unicode__(self):
|
|
||||||
return unicode(self.tag)
|
|
||||||
|
|
||||||
class Question(models.Model):
|
|
||||||
question = models.CharField(max_length=200)
|
|
||||||
description = models.CharField(max_length=800)
|
|
||||||
tags = models.ManyToManyField(Tag)
|
|
||||||
|
|
||||||
def __unicode__(self):
|
|
||||||
return unicode(self.question)
|
|
||||||
|
|
||||||
class KeyValueMap(models.Model):
|
|
||||||
key = models.CharField(max_length=200)
|
|
||||||
value = models.CharField(max_length=300)
|
|
||||||
|
|
||||||
def __unicode__(self):
|
|
||||||
return u'%s=>%s' % (self.key, self.value)
|
|
||||||
|
|
||||||
class WordList(models.Model):
|
|
||||||
kind = models.CharField(max_length=100)
|
|
||||||
word = models.ForeignKey(Word, null=True, blank=True, related_name='wordlist_word')
|
|
||||||
words = models.ManyToManyField(Word, null=True, blank=True, related_name='wordlist_words')
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
from django.conf.urls import patterns, url
|
|
||||||
|
|
||||||
urlpatterns = patterns('testapp.testmain.views',
|
|
||||||
url(r'single/model/field/$', 'test_single_value_model_field', name='test_single_value_model_field'),
|
|
||||||
url(r'single/model/field/([0-9]+)/$', 'test_single_value_model_field1', name='test_single_value_model_field1'),
|
|
||||||
|
|
||||||
url(r'multi/model/field/$', 'test_multi_values_model_field', name='test_multi_values_model_field'),
|
|
||||||
url(r'multi/model/field/([0-9]+)/$', 'test_multi_values_model_field1', name='test_multi_values_model_field1'),
|
|
||||||
|
|
||||||
url(r'mixed/form/$', 'test_mixed_form', name='test_mixed_form'),
|
|
||||||
|
|
||||||
url(r'initial/form/$', 'test_init_values', name='test_init_values'),
|
|
||||||
|
|
||||||
url(r'question/$', 'test_list_questions', name='test_list_questions'),
|
|
||||||
url(r'question/form/([0-9]+)/$', 'test_tagging', name='test_tagging'),
|
|
||||||
url(r'question/form/([0-9]+)/na/$', 'test_tagging_non_auto', name='test_tagging_non_auto'),
|
|
||||||
url(r'question/form/$', 'test_tagging_new', name='test_tagging_new'),
|
|
||||||
url(r'question/tags/$', 'test_tagging_tags', name='test_tagging_tags'),
|
|
||||||
|
|
||||||
url(r'auto_model/form/$', 'test_auto_multivalue_field', name='test_auto_multivalue_field'),
|
|
||||||
|
|
||||||
url(r'auto_heavy/perf_test/$', 'test_auto_heavy_perf', name='test_auto_heavy_perf'),
|
|
||||||
|
|
||||||
url(r'get_search/get_search_test/$', 'test_get_search_form', name='test_get_search_form'),
|
|
||||||
|
|
||||||
url(r'issue76/$', 'test_issue_73', name='test_issue_73'),
|
|
||||||
)
|
|
||||||
|
|
@ -1,165 +0,0 @@
|
||||||
import json
|
|
||||||
from django.core.urlresolvers import reverse
|
|
||||||
from django.http import HttpResponseRedirect, HttpResponse
|
|
||||||
from django.shortcuts import render, get_object_or_404
|
|
||||||
|
|
||||||
from .forms import EmployeeForm, DeptForm, MixedForm, InitialValueForm, QuestionForm, QuestionNonAutoForm, WordsForm, SchoolForm, \
|
|
||||||
GetSearchTestForm, AnotherWordForm
|
|
||||||
from .models import Employee, Dept, Question, WordList, School, Tag
|
|
||||||
|
|
||||||
def test_single_value_model_field(request):
|
|
||||||
return render(request, 'list.html', {
|
|
||||||
'title': 'Employees',
|
|
||||||
'href': 'test_single_value_model_field1',
|
|
||||||
'object_list': Employee.objects.all(),
|
|
||||||
'create_new_href': ''
|
|
||||||
})
|
|
||||||
|
|
||||||
def test_single_value_model_field1(request, id):
|
|
||||||
emp = get_object_or_404(Employee, pk=id)
|
|
||||||
if request.POST:
|
|
||||||
form = EmployeeForm(data=request.POST, instance=emp)
|
|
||||||
if form.is_valid():
|
|
||||||
form.save()
|
|
||||||
return HttpResponseRedirect(reverse('home'))
|
|
||||||
else:
|
|
||||||
form = EmployeeForm(instance=emp)
|
|
||||||
return render(request, 'form.html', {'form': form})
|
|
||||||
|
|
||||||
|
|
||||||
def test_multi_values_model_field(request):
|
|
||||||
return render(request, 'list.html', {
|
|
||||||
'title': 'Departments',
|
|
||||||
'href': 'test_multi_values_model_field1',
|
|
||||||
'object_list': Dept.objects.all(),
|
|
||||||
'create_new_href': ''
|
|
||||||
})
|
|
||||||
|
|
||||||
def test_multi_values_model_field1(request, id):
|
|
||||||
dept = get_object_or_404(Dept, pk=id)
|
|
||||||
if request.POST:
|
|
||||||
form = DeptForm(data=request.POST, instance=dept)
|
|
||||||
if form.is_valid():
|
|
||||||
form.save()
|
|
||||||
return HttpResponseRedirect(reverse('home'))
|
|
||||||
else:
|
|
||||||
form = DeptForm(instance=dept)
|
|
||||||
return render(request, 'form.html', {'form': form})
|
|
||||||
|
|
||||||
def test_mixed_form(request):
|
|
||||||
if request.POST:
|
|
||||||
form = MixedForm(request.POST)
|
|
||||||
form.is_valid()
|
|
||||||
else:
|
|
||||||
form = MixedForm()
|
|
||||||
return render(request, 'form.html', {'form': form})
|
|
||||||
|
|
||||||
def test_init_values(request):
|
|
||||||
return render(request, 'form.html', {'form': InitialValueForm()})
|
|
||||||
|
|
||||||
def test_list_questions(request):
|
|
||||||
return render(request, 'list.html', {
|
|
||||||
'title': 'Questions',
|
|
||||||
'href': 'test_tagging',
|
|
||||||
'href_non_auto': 'test_tagging_non_auto',
|
|
||||||
'object_list': Question.objects.all(),
|
|
||||||
'create_new_href': 'test_tagging_new'
|
|
||||||
})
|
|
||||||
|
|
||||||
def test_tagging_new(request):
|
|
||||||
return test_tagging(request, None)
|
|
||||||
|
|
||||||
def test_tagging(request, id):
|
|
||||||
if id is None:
|
|
||||||
question = Question()
|
|
||||||
else:
|
|
||||||
question = get_object_or_404(Question, pk=id)
|
|
||||||
if request.POST:
|
|
||||||
form = QuestionForm(data=request.POST, instance=question)
|
|
||||||
if form.is_valid():
|
|
||||||
form.save()
|
|
||||||
return HttpResponseRedirect(reverse('home'))
|
|
||||||
else:
|
|
||||||
form = QuestionForm(instance=question)
|
|
||||||
return render(request, 'form.html', {'form': form})
|
|
||||||
|
|
||||||
def test_tagging_non_auto(request, id):
|
|
||||||
if id is None:
|
|
||||||
question = Question()
|
|
||||||
else:
|
|
||||||
question = get_object_or_404(Question, pk=id)
|
|
||||||
if request.POST:
|
|
||||||
form = QuestionNonAutoForm(data=request.POST, instance=question)
|
|
||||||
if form.is_valid():
|
|
||||||
form.save()
|
|
||||||
return HttpResponseRedirect(reverse('home'))
|
|
||||||
else:
|
|
||||||
form = QuestionNonAutoForm(instance=question)
|
|
||||||
return render(request, 'form.html', {'form': form})
|
|
||||||
|
|
||||||
def test_tagging_tags(request):
|
|
||||||
tags = Tag.objects.all()
|
|
||||||
results = [{'id': t.id, 'text': t.tag} for t in tags]
|
|
||||||
return HttpResponse(json.dumps({'err': 'nil', 'results': results}), content_type='application/json')
|
|
||||||
|
|
||||||
def test_auto_multivalue_field(request):
|
|
||||||
try:
|
|
||||||
s = School.objects.get(id=1)
|
|
||||||
except School.DoesNotExist:
|
|
||||||
s = School(id=1)
|
|
||||||
|
|
||||||
if request.POST:
|
|
||||||
form = SchoolForm(data=request.POST, instance=s)
|
|
||||||
if form.is_valid():
|
|
||||||
form.save()
|
|
||||||
return HttpResponseRedirect(reverse('home'))
|
|
||||||
else:
|
|
||||||
form = SchoolForm(instance=s)
|
|
||||||
return render(request, 'form.html', {'form': form})
|
|
||||||
|
|
||||||
def test_auto_heavy_perf(request):
|
|
||||||
try:
|
|
||||||
word = WordList.objects.get(kind='Word_Of_Day')
|
|
||||||
except WordList.DoesNotExist:
|
|
||||||
word = WordList(kind='Word_Of_Day')
|
|
||||||
|
|
||||||
if request.POST:
|
|
||||||
form = WordsForm(data=request.POST, instance=word)
|
|
||||||
if form.is_valid():
|
|
||||||
form.save()
|
|
||||||
return HttpResponseRedirect(reverse('home'))
|
|
||||||
else:
|
|
||||||
form = WordsForm(instance=word)
|
|
||||||
return render(request, 'form.html', {'form': form})
|
|
||||||
|
|
||||||
def test_get_search_form(request):
|
|
||||||
"""
|
|
||||||
Test a search form using GET. Issue#66
|
|
||||||
"""
|
|
||||||
if request.GET:
|
|
||||||
form = GetSearchTestForm(request.GET)
|
|
||||||
if form.is_valid():
|
|
||||||
results = Employee.objects.all()
|
|
||||||
if form.cleaned_data['name'] != []:
|
|
||||||
results = results.filter(name__in = form.cleaned_data['name'])
|
|
||||||
if form.cleaned_data['dept'] != []:
|
|
||||||
results = results.filter(dept__in = form.cleaned_data['dept'])
|
|
||||||
else:
|
|
||||||
form = GetSearchTestForm()
|
|
||||||
results = Employee.objects.none()
|
|
||||||
return render(request, 'formget.html', {'form': form, 'results' : results})
|
|
||||||
|
|
||||||
def test_issue_73(request):
|
|
||||||
try:
|
|
||||||
word = WordList.objects.get(kind='Word_Of_Day')
|
|
||||||
except WordList.DoesNotExist:
|
|
||||||
word = WordList(kind='Word_Of_Day')
|
|
||||||
|
|
||||||
if request.POST:
|
|
||||||
form = AnotherWordForm(request.POST)
|
|
||||||
if form.is_valid():
|
|
||||||
form.save()
|
|
||||||
return HttpResponseRedirect(reverse('home'))
|
|
||||||
else:
|
|
||||||
form = AnotherWordForm(instance=word)
|
|
||||||
return render(request, 'form.html', {'form': form})
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
from django.conf.urls import patterns, include, url
|
|
||||||
from django.views.generic import TemplateView
|
|
||||||
from django.contrib import admin
|
|
||||||
|
|
||||||
admin.autodiscover()
|
|
||||||
|
|
||||||
urlpatterns = patterns('',
|
|
||||||
url(r'^admin/', include(admin.site.urls)),
|
|
||||||
url(r'^$', TemplateView.as_view(template_name="index.html"), name='home'),
|
|
||||||
url(r'^test/', include('testapp.testmain.urls')),
|
|
||||||
url(r'^ext/', include('django_select2.urls')),
|
|
||||||
)
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
"""
|
|
||||||
WSGI config for testapp project.
|
|
||||||
|
|
||||||
This module contains the WSGI application used by Django's development server
|
|
||||||
and any production WSGI deployments. It should expose a module-level variable
|
|
||||||
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
|
|
||||||
this application via the ``WSGI_APPLICATION`` setting.
|
|
||||||
|
|
||||||
Usually you will have the standard Django WSGI application here, but it also
|
|
||||||
might make sense to replace the whole Django WSGI application with a custom one
|
|
||||||
that later delegates to the Django one. For example, you could introduce WSGI
|
|
||||||
middleware here, or combine a Django application with an application of another
|
|
||||||
framework.
|
|
||||||
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
|
|
||||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testapp.settings")
|
|
||||||
|
|
||||||
# This application object is used by any WSGI server configured to use this
|
|
||||||
# file. This includes Django's development server, if the WSGI_APPLICATION
|
|
||||||
# setting points here.
|
|
||||||
from django.core.wsgi import get_wsgi_application
|
|
||||||
application = get_wsgi_application()
|
|
||||||
|
|
||||||
# Apply WSGI middleware here.
|
|
||||||
# from helloworld.wsgi import HelloWorldApplication
|
|
||||||
# application = HelloWorldApplication(application)
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
__author__ = 'johannes'
|
|
||||||
|
|
@ -1,50 +1,64 @@
|
||||||
# -*- coding:utf-8 -*-
|
import random
|
||||||
from __future__ import absolute_import, print_function, unicode_literals
|
import string
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from django import conf
|
|
||||||
from selenium import webdriver
|
from selenium import webdriver
|
||||||
from selenium.common.exceptions import WebDriverException
|
from selenium.common.exceptions import WebDriverException
|
||||||
|
|
||||||
|
|
||||||
def pytest_configure():
|
def random_string(n):
|
||||||
os.environ[conf.ENVIRONMENT_VARIABLE] = "tests.testapp.settings"
|
return ''.join(
|
||||||
|
random.choice(string.ascii_uppercase + string.digits)
|
||||||
|
for _ in range(n)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
try:
|
||||||
import django
|
b = webdriver.Chrome(options=chrome_options)
|
||||||
|
|
||||||
django.setup()
|
|
||||||
except AttributeError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
from django.test.utils import setup_test_environment
|
|
||||||
|
|
||||||
setup_test_environment()
|
|
||||||
|
|
||||||
from django.db import connection
|
|
||||||
|
|
||||||
connection.creation.create_test_db()
|
|
||||||
|
|
||||||
|
|
||||||
browsers = {
|
|
||||||
'firefox': webdriver.Firefox,
|
|
||||||
'chrome': webdriver.Chrome,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope='session',
|
|
||||||
params=browsers.keys())
|
|
||||||
def driver(request):
|
|
||||||
if 'DISPLAY' not in os.environ:
|
|
||||||
pytest.skip('Test requires display server (export DISPLAY)')
|
|
||||||
|
|
||||||
try:
|
|
||||||
b = browsers[request.param]()
|
|
||||||
except WebDriverException as e:
|
except WebDriverException as e:
|
||||||
pytest.skip(e)
|
pytest.skip(str(e))
|
||||||
else:
|
else:
|
||||||
b.set_window_size(1200, 800)
|
yield b
|
||||||
request.addfinalizer(lambda *args: b.quit())
|
b.quit()
|
||||||
return b
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def genres(db):
|
||||||
|
from .testapp.models import Genre
|
||||||
|
|
||||||
|
return Genre.objects.bulk_create(
|
||||||
|
[Genre(pk=pk, title=random_string(50)) for pk in range(100)]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def artists(db):
|
||||||
|
from .testapp.models import Artist
|
||||||
|
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)]
|
||||||
|
)
|
||||||
|
|
|
||||||
6
tests/test_cache.py
Normal file
6
tests/test_cache.py
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
def test_default_cache():
|
||||||
|
from django_select2.cache import cache
|
||||||
|
|
||||||
|
cache.set('key', 'value')
|
||||||
|
|
||||||
|
assert cache.get('key') == 'value'
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
from __future__ import print_function, unicode_literals
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from django.core.urlresolvers import reverse
|
|
||||||
from model_mommy import mommy
|
|
||||||
from selenium.common.exceptions import NoSuchElementException
|
|
||||||
|
|
||||||
|
|
||||||
class ViewTestMixin(object):
|
|
||||||
url = ''
|
|
||||||
|
|
||||||
def test_get(self, client):
|
|
||||||
response = client.get(self.url)
|
|
||||||
assert response.status_code == 200
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def genres(db):
|
|
||||||
mommy.make('testapp.Genre', _quantity=100)
|
|
||||||
|
|
||||||
|
|
||||||
class TestAutoModelSelect2TagField(object):
|
|
||||||
url = reverse('single_value_model_field')
|
|
||||||
|
|
||||||
def test_no_js_error(self, db, client, live_server, driver, genres):
|
|
||||||
driver.get(live_server + self.url)
|
|
||||||
with pytest.raises(NoSuchElementException):
|
|
||||||
error = driver.find_element_by_xpath('//body[@JSError]')
|
|
||||||
pytest.fail(error.get_attribute('JSError'))
|
|
||||||
531
tests/test_forms.py
Normal file
531
tests/test_forms.py
Normal file
|
|
@ -0,0 +1,531 @@
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from collections.abc import Iterable
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from django.core import signing
|
||||||
|
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 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
|
||||||
|
)
|
||||||
|
from tests.testapp import forms
|
||||||
|
from tests.testapp.forms import (
|
||||||
|
NUMBER_CHOICES, HeavySelect2MultipleWidgetForm, TitleModelSelect2Widget
|
||||||
|
)
|
||||||
|
from tests.testapp.models import Artist, City, Country, Genre, Groupie
|
||||||
|
|
||||||
|
|
||||||
|
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 str(genre) in form.as_p()
|
||||||
|
|
||||||
|
def test_initial_form_class(self):
|
||||||
|
widget = self.widget_cls(attrs={'class': 'my-class'})
|
||||||
|
assert 'my-class' in widget.render('name', None)
|
||||||
|
assert 'django-select2' in widget.render('name', None)
|
||||||
|
|
||||||
|
def test_allow_clear(self, db):
|
||||||
|
required_field = self.form.fields['artist']
|
||||||
|
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 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
|
||||||
|
assert 'data-allow-clear="true"' in not_required_field.widget.render('primary_genre', None)
|
||||||
|
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 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)
|
||||||
|
with pytest.raises(NoSuchElementException):
|
||||||
|
error = driver.find_element_by_xpath('//body[@JSError]')
|
||||||
|
pytest.fail(error.get_attribute('JSError'))
|
||||||
|
|
||||||
|
def test_selecting(self, db, live_server, driver):
|
||||||
|
driver.get(live_server + self.url)
|
||||||
|
with pytest.raises(NoSuchElementException):
|
||||||
|
driver.find_element_by_css_selector('.select2-results')
|
||||||
|
elem = driver.find_element_by_css_selector('.select2-selection')
|
||||||
|
elem.click()
|
||||||
|
results = driver.find_element_by_css_selector('.select2-results')
|
||||||
|
assert results.is_displayed() is True
|
||||||
|
elem = results.find_element_by_css_selector('.select2-results__option')
|
||||||
|
elem.click()
|
||||||
|
|
||||||
|
with pytest.raises(NoSuchElementException):
|
||||||
|
error = driver.find_element_by_xpath('//body[@JSError]')
|
||||||
|
pytest.fail(error.get_attribute('JSError'))
|
||||||
|
|
||||||
|
def test_data_url(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
HeavySelect2Widget()
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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 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):
|
||||||
|
settings.SELECT2_JS = 'alternate.js'
|
||||||
|
sut = Select2Widget()
|
||||||
|
result = sut.media.render()
|
||||||
|
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')
|
||||||
|
form = forms.HeavySelect2WidgetForm(initial={'primary_genre': 1})
|
||||||
|
widget_cls = HeavySelect2Widget
|
||||||
|
|
||||||
|
def test_initial_data(self):
|
||||||
|
assert 'One' in self.form.as_p()
|
||||||
|
|
||||||
|
def test_initial_form_class(self):
|
||||||
|
widget = self.widget_cls(data_view='heavy_data_1', attrs={'class': 'my-class'})
|
||||||
|
assert 'my-class' in widget.render('name', None)
|
||||||
|
assert 'django-select2' in widget.render('name', None)
|
||||||
|
assert 'django-select2-heavy' in widget.render('name', None), widget.render('name', None)
|
||||||
|
|
||||||
|
def test_selected_option(self, db):
|
||||||
|
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) 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):
|
||||||
|
field = HeavySelect2MultipleWidgetForm().fields['genres']
|
||||||
|
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 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)
|
||||||
|
with pytest.raises(NoSuchElementException):
|
||||||
|
driver.find_element_by_css_selector('.select2-results')
|
||||||
|
|
||||||
|
elem1, elem2 = driver.find_elements_by_css_selector('.select2-selection')
|
||||||
|
|
||||||
|
elem1.click()
|
||||||
|
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()
|
||||||
|
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
|
||||||
|
|
||||||
|
with pytest.raises(NoSuchElementException):
|
||||||
|
error = driver.find_element_by_xpath('//body[@JSError]')
|
||||||
|
pytest.fail(error.get_attribute('JSError'))
|
||||||
|
|
||||||
|
def test_get_url(self):
|
||||||
|
widget = self.widget_cls(data_view='heavy_data_1', attrs={'class': 'my-class'})
|
||||||
|
assert isinstance(widget.get_url(), str)
|
||||||
|
|
||||||
|
def test_can_not_pickle(self):
|
||||||
|
widget = self.widget_cls(data_view='heavy_data_1', attrs={'class': 'my-class'})
|
||||||
|
|
||||||
|
class NoPickle:
|
||||||
|
pass
|
||||||
|
|
||||||
|
widget.no_pickle = NoPickle()
|
||||||
|
with pytest.raises(NotImplementedError):
|
||||||
|
widget.set_to_cache()
|
||||||
|
|
||||||
|
|
||||||
|
class TestModelSelect2Mixin(TestHeavySelect2Mixin):
|
||||||
|
form = forms.AlbumModelSelect2WidgetForm(initial={'primary_genre': 1})
|
||||||
|
multiple_form = forms.ArtistModelSelect2MultipleWidgetForm()
|
||||||
|
|
||||||
|
def test_initial_data(self, genres):
|
||||||
|
genre = genres[0]
|
||||||
|
form = self.form.__class__(initial={'primary_genre': genre.pk})
|
||||||
|
assert str(genre) in form.as_p()
|
||||||
|
|
||||||
|
def test_label_from_instance_initial(self, genres):
|
||||||
|
genre = genres[0]
|
||||||
|
genre.title = genre.title.lower()
|
||||||
|
genre.save()
|
||||||
|
|
||||||
|
form = self.form.__class__(initial={'primary_genre': genre.pk})
|
||||||
|
assert genre.title not in form.as_p(), form.as_p()
|
||||||
|
assert genre.title.upper() in form.as_p()
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def genres(self, genres):
|
||||||
|
return genres
|
||||||
|
|
||||||
|
def test_selected_option(self, db, genres):
|
||||||
|
genre = genres[0]
|
||||||
|
genre2 = genres[1]
|
||||||
|
not_required_field = self.form.fields['primary_genre']
|
||||||
|
assert not_required_field.required is False
|
||||||
|
widget_output = not_required_field.widget.render(
|
||||||
|
'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 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):
|
||||||
|
genre = genres[0]
|
||||||
|
genre.title = genre.title.lower()
|
||||||
|
genre.save()
|
||||||
|
|
||||||
|
field = self.form.fields['primary_genre']
|
||||||
|
widget_output = field.widget.render('primary_genre', genre.pk)
|
||||||
|
|
||||||
|
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 all(o not in widget_output for o in get_selected_options(genre))
|
||||||
|
genre.title = genre.title.upper()
|
||||||
|
|
||||||
|
assert any(o in widget_output for o in get_selected_options(genre))
|
||||||
|
|
||||||
|
def test_get_queryset(self):
|
||||||
|
widget = ModelSelect2Widget()
|
||||||
|
with pytest.raises(NotImplementedError):
|
||||||
|
widget.get_queryset()
|
||||||
|
widget.model = Genre
|
||||||
|
assert isinstance(widget.get_queryset(), QuerySet)
|
||||||
|
widget.model = None
|
||||||
|
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(), 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(None, genres[0].title[:3]).exists()
|
||||||
|
|
||||||
|
widget = TitleModelSelect2Widget(search_fields=['title__icontains'],
|
||||||
|
queryset=Genre.objects.all())
|
||||||
|
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(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(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: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
|
||||||
|
data = json.loads(response.content.decode('utf-8'))
|
||||||
|
assert data['results']
|
||||||
|
assert genre.pk in [result['id'] for result in data['results']]
|
||||||
|
|
||||||
|
def test_render(self):
|
||||||
|
widget = ModelSelect2Widget(queryset=Genre.objects.all())
|
||||||
|
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'] == tuple(widget.search_fields)
|
||||||
|
qs = widget.get_queryset()
|
||||||
|
assert isinstance(cached_widget['queryset'][0], qs.__class__)
|
||||||
|
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(), 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):
|
||||||
|
|
||||||
|
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="2"' in output
|
||||||
|
assert 'data-tags="true"' in output
|
||||||
|
assert 'data-token-separators' in output
|
||||||
|
|
||||||
|
def test_custom_tag_attrs(self):
|
||||||
|
widget = ModelSelect2TagWidget(
|
||||||
|
queryset=Genre.objects.all(), search_fields=['title__icontains'], attrs={'data-minimum-input-length': '3'})
|
||||||
|
output = widget.render('name', 'value')
|
||||||
|
assert 'data-minimum-input-length="3"' in output
|
||||||
|
|
||||||
|
|
||||||
|
class TestHeavySelect2MultipleWidget:
|
||||||
|
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')
|
||||||
|
genres.click()
|
||||||
|
genres.send_keys('o') # results are Zero One Two Four
|
||||||
|
# select second element - One
|
||||||
|
driver.find_element_by_css_selector('.select2-results li:nth-child(2)').click()
|
||||||
|
genres.submit()
|
||||||
|
# there is a ValidationError raised, check for it
|
||||||
|
errstring = 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
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue