Package: django-select2-forms
django-select2-formsis a project that makes available Django form
fields that use theSelect2 javascript
plugin. It was created by
developers atThe Atlantic.Table of Contents:SupportLocal Development & TestingInstallpyenvPython Repository SetupActivate Your EnvironmentRunning testsInstallationConfigurationUsageselect2.fields.ForeignKey examplesselect2.fields.ManyToManyField examplesform field exampleLicenseSupportBeing that Django added select2 support in 2.0, we will support up to that version
for compatibility purposes.~=v3.0: Python >=3.7,<3.9 | Django 2.2,3.1,3.2 (current release)Local Development & TestingThe following steps should only need to be done once when you first begin:InstallpyenvThese instructions assume that you haveHomebrewinstalled,
but notpyenv.brewinstallpyenvtouch~/.bash_profileAdd the following line to your~/bash_profileor.zshrc:eval "$(pyenv init -)"Reload your shell:.~/.bash_profileor.~/.zshrcPython Repository SetupFirst, clone the repository and prep your Python environment:gitclonehttps://github.com/theatlantic/django-select2-forms.gitpyenvinstall3.7.2pyenvinstall3.8.0pyenvinstall3.9.0pyenvlocal3.7.23.8.03.9.0python-VThe output of the previous command should bePython 3.7.2.Finally:python-mvenvvenvActivate Your EnvironmentFrom the base directory:deactivate# ignore: -bash: deactivate: command not found.venv/bin/activatepipinstall-UtoxRunning testsIf you have not already done so, set up your environment by chromedriver:brewinstall--caskchromedriverRun all tests:tox----selenosis-driver=chrome-headlessShow all availabletoxcommands:tox-avRun only a specific environment:tox-e<environment-name>----selenosis-driver=chrome-headless# example: tox -e py37-django22Only run a specific test:tox--pytest-ktest_something--selenosis-driver=chrome-headlessRun an arbitrary command in a specific environment:tox-epy37-django22--python# runs the Python REPL in that environmentSetup a development environment:tox-e<pyXX-DjangoYY>--develop-r..tox/<pyXX-DjangoYY>/bin/activateInstallationThe recommended way to install is with pip:pip install django-select2-formsor, to install with pip from source:pip install -e git+git://github.com/theatlantic/django-select2-forms.git#egg=django-select2-formsIf the source is already checked out, use setuptools:python setup.py developConfigurationdjango-select2-formsserves static assets usingdjango.contrib.staticfiles,
and so requires that"select2"be added to your settings’INSTALLED_APPS:INSTALLED_APPS=(# ...'select2',)To use django-select2-forms’ ajax support,'select2.urls'must be
included in your urls.pyurlpatterns:urlpatterns=patterns('',# ...url(r'^select2/',include('select2.urls')),)UsageThe simplest way to usedjango-select2-formsis to useselect2.fields.ForeignKeyandselect2.fields.ManyToManyFieldin
place ofdjango.db.models.ForeignKeyanddjango.db.models.ManyToManyField, respectively. These fields extend
their django equivalents and take the same arguments, along with extra
optional keyword arguments.select2.fields.ForeignKey examplesIn the following two examples, an “entry” is associated with only one
author. The example below does not use ajax, but instead performs
autocomplete filtering on the client-side using the<option>elements (the labels of which are drawn fromAuthor.__str__())
in an html<select>.@python_2_unicode_compatibleclassAuthor(models.Model):name=models.CharField(max_length=100)def__str__(self):returnself.nameclassEntry(models.Model):author=select2.fields.ForeignKey(Author,overlay="Choose an author...",on_delete=models.CASCADE)This more advanced example autocompletes via ajax using theAuthor.namefield and limits the autocomplete search toAuthor.objects.filter(active=True)classAuthor(models.Model):name=models.CharField(max_length=100)active=models.BooleanField()classEntry(models.Model):author=select2.fields.ForeignKey(Author,limit_choices_to=models.Q(active=True),ajax=True,search_field='name',overlay="Choose an author...",js_options={'quiet_millis':200,},on_delete=models.CASCADE)select2.fields.ManyToManyField examplesIn the following basic example, entries can have more than one author.
This example does not do author name lookup via ajax, but populates<option>elements in a<select>withAuthor.__unicode__()for labels.@python_2_unicode_compatibleclassAuthor(models.Model):name=models.CharField(max_length=100)def__str__(self):returnself.nameclassEntry(models.Model):authors=select2.fields.ManyToManyField(Author)The following “kitchen sink” example allows authors to be ordered, and
uses ajax to autocomplete on two variants of an author’s name.fromdjango.dbimportmodelsfromdjango.db.modelsimportQimportselect2.fieldsimportselect2.modelsclassAuthor(models.Model):name=models.CharField(max_length=100)alt_name=models.CharField(max_length=100,blank=True,null=True)classEntry(models.Model):categories=select2.fields.ManyToManyField(Author,through='EntryAuthors',ajax=True,search_field=lambdaq:Q(name__icontains=q)|Q(alt_name__icontains=q),sort_field='position',js_options={'quiet_millis':200})form field exampleIf you don’t need to use the ajax features ofdjango-select2-formsit is possible to use select2 on django forms without modifying your
models. The select2 formfields exist in theselect2.fieldsmodule
and have the same class names as their standard django counterparts
(ChoiceField,MultipleChoiceField,ModelChoiceField,ModelMultipleChoiceField). Here is the firstForeignKeyexample
above, done with django formfields.classAuthorManager(models.Manager):defas_choices(self):forauthorinself.all():yield(author.pk,force_text(author))@python_2_unicode_compatibleclassAuthor(models.Model):name=models.CharField(max_length=100)objects=AuthorManager()def__str__(self):returnself.nameclassEntry(models.Model):author=models.ForeignKey(Author,on_delete=models.CASCADE)classEntryForm(forms.ModelForm):author=select2.fields.ChoiceField(choices=Author.objects.as_choices(),overlay="Choose an author...")classMeta:model=EntryLicenseThe django code is licensed under theSimplified BSD
Licenseand is
copyright The Atlantic Media Company. View theLICENSEfile under
the root directory for complete license and copyright information.The Select2 javascript library included is licensed under theApache
Software Foundation License Version
2.0. View the fileselect2/static/select2/select2/LICENSEfor complete license and
copyright information about the Select2 javascript library.