Django-Select2¶
Custom autocomplete fields forDjango.
Documentation¶
Documentation available athttps://django-select2.readthedocs.io/.
Note
Django’s admin comes with builtin support for Select2via theautocomplete_fields feature.
Installation¶
Installdjango-select2
:
python3-mpipinstalldjango-select2
Adddjango_select2
to yourINSTALLED_APPS
in your project settings.Since version 8, please ensure that Django’s admin app is enabled too:
INSTALLED_APPS=[# other django apps…'django.contrib.admin',# other 3rd party apps…'django_select2',]
Adddjango_select
to your URL root configuration:
fromdjango.urlsimportinclude,pathurlpatterns=[# other patterns…path("select2/",include("django_select2.urls")),# other patterns…]
TheModel -widgets require apersistent cache backend acrossall application servers. This is because the widget needs to storemeta data to be able to fetch the results based on the user input.
This means that theDummyCache
backend will not work!
The default cache backend isLocMemCache
, which is persistentacross a single node. For projects with a single application serverthis will work fine, however you will run into issues whenyou scale up into multiple servers.
Below is an example setup using Redis, which is a solution thatworks for multi-server setups:
Make sure you have a Redis server up and running:
# Debiansudoapt-getinstallredis-server# macOSbrewinstallredis# install Redis python clientpython3-mpipinstalldjango-redis
Next, add the cache configuration to yoursettings.py
as follows:
CACHES={# … default cache config and others"select2":{"BACKEND":"django_redis.cache.RedisCache","LOCATION":"redis://127.0.0.1:6379/2","OPTIONS":{"CLIENT_CLASS":"django_redis.client.DefaultClient",}}}# Tell select2 which cache configuration to use:SELECT2_CACHE_BACKEND="select2"
Note
A custom timeout for your cache backend, will serve as an indirect session limit.Auto select fields will stop working after, once the cache has expired.It’s recommended to use a dedicated cache database with an adequatecache replacement policy such as LRU, FILO, etc.
External Dependencies¶
jQuery is not included in the package since it isexpected that in most scenarios this would already be available.
Quick Start¶
Here is a quick example to get you started:
First make sure you followed the installation instructions above.Once everything is setup, let’s start with a simple example.
We have the following model:
# models.pyfromdjango.confimportsettingsfromdjango.dbimportmodelsclassBook(models.Model):author=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)co_authors=models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='co_authored_by')
Next, we create a model form with custom Select2 widgets.
# forms.pyfromdjangoimportformsfromdjango_select2importformsass2formsfrom.importmodelsclassAuthorWidget(s2forms.ModelSelect2Widget):search_fields=["username__icontains","email__icontains",]classCoAuthorsWidget(s2forms.ModelSelect2MultipleWidget):search_fields=["username__icontains","email__icontains",]classBookForm(forms.ModelForm):classMeta:model=models.Bookfields="__all__"widgets={"author":AuthorWidget,"co_authors":CoAuthorsWidget,}
A simple class based view will do, to render your form:
# views.pyfromdjango.viewsimportgenericfrom.importforms,modelsclassBookCreateView(generic.CreateView):model=models.Bookform_class=forms.BookFormsuccess_url="/"
Make sure to add the view to yoururls.py
:
# urls.pyfromdjango.urlsimportinclude,pathfrom.importviewsurlpatterns=[# … other patternspath("select2/",include("django_select2.urls")),# … other patternspath("book/create",views.BookCreateView.as_view(),name="book-create"),]
Finally, we need a little template,myapp/templates/myapp/book_form.html
<!DOCTYPE html><htmllang="en"><head><title>Create Book</title> {{ form.media.css }}<style>input,select{width:100%}</style></head><body><h1>Create a new Book</h1><formmethod="POST"> {% csrf_token %} {{ form.as_p }}<inputtype="submit"></form><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {{ form.media.js }}</body></html>
Done - enjoy the wonders of Select2!
Changelog¶
SeeGithub releases.
All Contents¶
Contents: