Code Monkey home page Code Monkey logo

django-easy-select2's Introduction

This is django application that brings select2 widget to select inputs in admin.


Python 3.x pypi GitHub Action "Run tox" coverage MIT License

Project aims to support Python 3.7+ and Django 2.2+.

For Django < 2.0 version support or python-2.x compatibility, please use version 1.3.4 which is the last version to support python-2.x compatibility.

For Django 2.0/2.1 version support or Python 3.5/3.6 compatibility, please use version 1.5.7 which is the last version to support Django 2.0/2.1 and Python 3.5/3.6 compatibility.

This django library is just a lightweight wrapper on Select2 library and provides easy-to-use basic select2 functionality in a django project. If you need feature-rich solution, i recommend you to look at the latest django-select2 library, which have ajax loading support.

If anyone really wants this functionality in django-easy-select2, please feel free to contribute.

Currently project is not in active development state and is maintained by community. Pull requests are welcomed!

Upgrade notes

For details please read changelog.

How it looks

Select one of existing values with single-valued choice field (ForeignKeyField, for example):

image

Easily select 1 or more "categories" for your project, you can also add a new one in the normal, Django-Admin manner by using the green + button with multiple-valued choice field (ManyToManyField):

image

Quickstart

In your admin.py:

from django.contrib import admin
from easy_select2 import select2_modelform
from polls.models import Poll

PollForm = select2_modelform(Poll, attrs={'width': '250px'})

class PollAdmin(admin.ModelAdmin):
    form = PollForm

Thats all. All your choice widgets are select2 widgets 250px wide.

Documentation

You can read more in the documentation.

django-easy-select2's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-easy-select2's Issues

Git tags missing for releases 1.4.0 to 1.5.7 ?

Hi!

Is there a specific reason when release from 1.4.0 on do not have Git release tags in here any more? Do you have local tags that you didn't push? Would you welcome help finding the releated commits to create the missings tags?

Best, Sebastian

Newly added foreign element don't display and many to many relation couldn't add item

I have configured django easy select according to document, it's working fine but when I add new item to foreign key field it's actually selected but it isn't displayed in UI that whatanelement selected. after adding new element from pop up any element I choose it will only display None.

For many to many field it doesn't add item.

python==3.5.2
Django==2.0.2
django-easy-select2==1.3.4


For now I have to either refresh page or press save and continue editing so that I can add/select item(s) after newly added item.

Easy Select2 does not work with 1.11

Hi,
Easy Select 2 does not seem to be working with 1.11(the latest release). The last known release to work on is 1.10.7

Attached is the screenshot of the error.

screen shot 2017-04-17 at 2 47 03 pm

Sample project does not work?

After I run python manage.py migrate (the docs still say syncdb), then I use:

python manage.py runserver 

But no admin is available and the project does not show up on the root either?

Included js/css blocked by no-sniff header

The files included by using the widgets are downloaded as text/html and but they are included as application/javascript.
If you're including a no-sniff header on all your pages you get an error like the following:

The resource from “https://192.168.60.201/site_media/easy_select2/js/easy_select2.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
So questions:
Why are these files being downloaded by the brower as text/html, when they are being included like:

<script type="text/javascript" src="/site_media/easy_select2/js/init.js"></script>

Is there any way to override how they are being included?

Django 4.0 ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'

I upgraded Django to 4.0 and I'm getting an error:

  File "easy_select2/__init__.py", line 1, in <module>
    from easy_select2.utils import select2_modelform_meta, select2_modelform, \
  File "easy_select2/utils.py", line 5, in <module>
    from easy_select2 import forms as es2_forms
  File "easy_select2/forms.py", line 5, in <module>
    from django.utils.translation import ugettext_lazy as _
ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (django/utils/translation/__init__.py)

We need to change ugettext_lazy to gettext_lazy

Docs : Usage of Select2Multiple error

EVN django 1.11.7
class Form(forms.Form):
field = forms.ModelChoiceField(queryset=qs, widget=Select2Multiple(
select2attrs={'width': 'auto'}
))

should be

class Form(forms.Form):
field = forms.ModelMultipleChoiceField(queryset=qs, widget=Select2Multiple(
select2attrs={'width': 'auto'}
))

Select2 is not being rendered

Hi. I installed the latest version of django-easy-select2 with pip on Django 4.0.3. When I use it on a model form like below, nothing happens, although the element is rendered to the HTML (image).

class MyForm(forms.ModelForm):
    myfield = forms.ModelMultipleChoiceField(widget=Select2Multiple(select2attrs={'width': 'auto'})

image

Any fix on this?

app breaks dumpdata

After adding 'easy_select2' to installed apps I am not able to run the python manage.py dumpdata command anymore.

It says:
CommandError: Unable to serialize database: no such table: easy_select2_related

if I run it with traceback I get:

Traceback (most recent call last):
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: easy_select2_related

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/core/management/commands/dumpdata.py", line 167, in handle
    object_count=object_count)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/core/serializers/__init__.py", line 129, in serialize
    s.serialize(queryset, **options)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/core/serializers/base.py", line 79, in serialize
    for count, obj in enumerate(queryset, start=1):
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/core/management/commands/dumpdata.py", line 150, in get_objects
    for obj in queryset.iterator():
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/models/query.py", line 52, in __iter__
    results = compiler.execute_sql()
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql
    cursor.execute(sql, params)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/utils.py", line 95, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/zoli/projects/test_de2/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: easy_select2_related

Python version: Python 3.5.1+
Installed packages:

Django==1.9.7
django-easy-select2==1.3.2
pkg-resources==0.0.0

This app has models.py but no migrations so I tried to makemigrations and run them but it didn't help.

Adding Mood in Sample App broken

Hey,

I started the demo app according to the guidelines and wanted to test the addition of Moods. Did not work: Entering texts, adn pressing RET did nothing. Saving did not help either. Am I doing sth wrong, or is it broken?

$ pip freeze
Django==1.7
argparse==1.2.1
-e git+https://github.com/asyncee/django-easy-select2.git@9472163506cd906a7a2219099f45473f41f902a5#egg=django_easy_select2-origin/develop
wsgiref==0.1.2

selection_212

Cheers,
murat

Brilliant! But, how can I get it to work alongside django-sortableadmin?

This is a brilliant app, thank you for building it and sharing it.

I'm struggling to make it work alongside django-sortableadmin. In particular, I'm attempting to use a SortableTabularInline that also uses easy-select2.

I've experimented with setting SELECT2_USE_BUNDLED_JQUERY = False, thinking perhaps there's a JS conflict of some sort, but that didn't seem to help. =/

Any ideas?

Select will not update selection after adding a new option

In the sample application, while creating a new Note I can create a new Category (clicking in the plus sign next to the select). The new category is created correctly, and I can see in the database, the select for the categories is not updated until reload of the page.

If I save the new Note inmediately after the Category is created (without reloading the page), then the Note has the category created.

question: ArrayField support

Hi,

Not sure if I am asking the right thing here, but could you please share an example
of saving a list coming from django-easy-select2 in PostgreSQL array field ?

In other words, is Django ArrayField supported ?

Update included version to 4.0.13

I just noticed the included version appears to be pinned to 4.0.0, which was released about 5 years ago. Looking through the code, there shouldn't be anything breaking when doing this change and it will fix a lot of accessibility and browser compatibility issues that have been spotted over the years.

caching static files with CachedStaticFilesStorage

Hi,

I use your package and I want to have my static files cached but when I have no static files collected, empty cache and DEBUG set to False I end up with such exception using any of manage.py commands:

$ python manage.py 
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/somewhere/lib/python3.4/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "/somewhere/lib/python3.4/site-packages/django/core/management/__init__.py", line 328, in execute
    django.setup()
  File "/somewhere/lib/python3.4/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/somewhere/lib/python3.4/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/somewhere/lib/python3.4/site-packages/django/apps/config.py", line 86, in create
    module = import_module(entry)
  File "/somewhere/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/somewhere/lib/python3.4/site-packages/easy_select2/__init__.py", line 6, in <module>
    from easy_select2.utils import (
  File "/somewhere/lib/python3.4/site-packages/easy_select2/utils.py", line 7, in <module>
    from easy_select2.widgets import Select2Mixin, Select2, Select2Multiple
  File "/somewhere/lib/python3.4/site-packages/easy_select2/widgets.py", line 32, in <module>
    static('easy_select2/js/init.js'),
  File "/somewhere/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 131, in url
    hashed_name = self.stored_name(clean_name)
  File "/somewhere/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 280, in stored_name
    cache_name = self.clean_name(self.hashed_name(name))
  File "/somewhere/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 94, in hashed_name
    (clean_name, self))
ValueError: The file 'easy_select2/js/init.js' could not be found with <django.contrib.staticfiles.storage.CachedStaticFilesStorage object at 0x000000000000>.

My workaround is to set DEBUG to True, run python manage.py collectstatic, set it back to False. I use Django 1.8.8 and django-easy-select 1.3.1.

This works:

DEBUG = True
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'

or

DEBUG = False
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'  # default

This doesn't:

DEBUG = False
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'

Running python manage.py collectstatic with CachedStaticFilesStorage to collect static files requires static files to be already collected 😄 as opposed to default StaticFilesStorage.

Using tinyMCE reloads jQuery namespace, select2 registers in the new jQuery namespace

I have this weird script order, jquery loads , jquery-ui registers itself, jquery.init.js where jQuery name space is cleared and moved to django.jQuery.

  • Now, easy-select2 loads, no jQuery so fills it with django.jQuery and stored $ and _djq, both pointing to django.jQuery and remains that way due to closure.
  • Next tinymce's jQuery loads replaces jQuery namespace.
  • Next select2 load and register to the newly created jQuery namespace.
  • easy-select js nows tries to call select2 since it remembers only django.jQuery instance (due to closure) a error is thrown stating there is no function select2
<script type="text/javascript" src="/admin/jsi18n/"></script>
<link href="/static/tabbed_admin/css/jquery-ui-1.11.4.min.css" type="text/css" media="all" rel="stylesheet">
<link href="/static/tabbed_admin/css/tabbed_admin.css" type="text/css" media="all" rel="stylesheet">
<link href="/static/easy_select2/vendor/select2/css/select2.min.css" type="text/css" media="screen" rel="stylesheet">
<link href="/static/easy_select2/css/easy_select2.css" type="text/css" media="screen" rel="stylesheet">
<script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script>
<script type="text/javascript" src="/static/tabbed_admin/js/jquery-ui-1.11.4.min.js"></script>
<script type="text/javascript" src="/static/easy_select2/js/init.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/easy_select2/js/easy_select2.js"></script>
<script type="text/javascript" src="/static/django_tinymce/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/easy_select2/vendor/select2/js/select2.min.js"></script>
<script type="text/javascript" src="/static/django_tinymce/init_tinymce.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.js"></script>
<script type="text/javascript" src="/static/admin/js/urlify.js"></script>
<script type="text/javascript" src="/static/admin/js/prepopulate.js"></script>
<script type="text/javascript" src="/static/admin/js/vendor/xregexp/xregexp.js"></script>

Support passing themes?

Hi!

I would like to use the bootstrap4 theme for Select2. The way to activate it would be:

$('select').select2({
    theme: 'bootstrap4',
});

To make that work with django-easy-select2 it seems I would need to pass theme: 'bootstrap4' here:

_jq(document).ready(function(){
// easy_select2() can take select2 constructor arguments object
_jq('body').easy_select();
});

If that's right, I wonder how to best bypass just easy_select2/js/init.js as a user and load a custom copy. Any thoughts? Would a PR adding a new setting work?

Best, Sebastian

raw_id_fields not working, exclude and fields in customized form not working!

hi!
i use django 2.2.5 and django-easy-select2 1.5.6
i have two problem

  1. raw_id_fields not working by select2_modelform
  2. fields or exclude in custome form not working by select2_modelform

for example:

class PageUpdateAdminForm(forms.ModelForm):
	class Meta:
		model = Page
		exclude = ('site', 'type')

@admin.register(Page)
class PageAdmin(AdminViewMixin, admin.ModelAdmin):
	form = select2_modelform(Page, form_class=PageUpdateAdminForm)
	raw_id_fields = ('user',)

the user field is showing by select2 and the exclude fields are exists in model form

Related model combobox doesn't update after add in Django 2

  1. cloned demoapp, pip install -U django
  2. setup demoapp, updated config and migrations to run under Django2
  3. run demo, logged in
  4. try to add new note - press plus; type in max into inputs, click save
  5. I've been returned to add note page but user combo still shows dashes ---------
  6. click on dropdown box and see there new option max
  7. click save note and note is saved with user max

I guess some problem in trigger('change'). In my django2 app I had to write window.$('select').trigger('change') instead of $('select').trigger('change').

autocomplete_fields inputs initialised twice

Note that I'm using SELECT2_USE_BUNDLED_JQUERY = False. So I am using the bundled django jquery (e.g. in the admin)

Since the last change introduced in #55, any autocomplete_fields (django 2+) are now initialised twice.

Not sure why, but removing these lines seems to solve my issue - could this be a solution that works for everyone?
Update: scrap all that, still trying to figure out what is the cause... will update soon

I believe the issue is with the new django-autocomplete-light rather (using both, so hard to tell). I will close until I know for sure and will re-open/recreate a new ticket if I find it's django-easy-select2

Ignored in production

I installed easy-select2 following the instructions in the doc and it works perfectly in my local environment. However, in production it seems to be completely ignored. Is there any reason why it would default back to the standard select widget?

widgets won't render and I don't know why

I have code like this:

from django import forms
from django_countries.fields import LazyTypedChoiceField, countries
from easy_select2.widgets import Select2Multiple

class LeadForm(forms.Form):
    overseas_company = forms.MultipleChoiceField(
        choices=countries,
        label='Do you have any companies overseas and where?',
        widget=Select2Multiple
    )

But it always renders like a normal forms.SelectMultiple. Your documentation doesn't really cover this case specifically, and I have no idea where to start troubleshooting. Any ideas? I even changed the import to easy_select2.widgets specifically.

Python 3 compatibility

I just forked the repo and made a few adjustments that make this work in my Python 3.3.3 environment. These are just a few changes, maybe you could make a version which runs on python 2 and 3

Drop support for Django … and Python …

Hi!

After PR #93 is merged, I consider making another PR dropping support for the following Django and Python versions:

  • Django
    • Django 2.0 — end-of-life already
    • Django 2.1 — end-of-life already
    • (Django 2.2 — end-of-life by 2022-05-01)
    • Django 3.0 — end-of-life already
    • Django 3.1 — end-of-life by 2022-01-01
  • Python
    • Python 3.5 — end-of-life already
    • Python 3.6 — end-of-life by 2022-12-23
    • (Python 3.8 — no particular need, save runtime and CO2, move coverage collection to (3.7 or) 3.10)
    • (Python 3.9 — no particular need, save runtime and CO2)

The ones in braces are controversial, and I am just voicing an opinion for discussion.

After a decision, the plan for the pull request would be to:

  • Introduce python_requires with >=3.7 to setup.py.
  • Introduce install_requires with e.g. Django>=3.2 to setup.py.
  • Drop things from tox.ini.
  • Drop things from CI YAML files.

What do you think?

Best, Sebastian

CC @asyncee @gauravv7 @mikekeda

Django 4.0 ImportError: cannot import name 'force_text' from 'django.utils.encoding'

I upgraded Django to 4.0 and I'm getting an error:

  File "//easy_select2/__init__.py", line 1, in <module>
    from easy_select2.utils import select2_modelform_meta, select2_modelform, \
  File "easy_select2/utils.py", line 5, in <module>
    from easy_select2 import forms as es2_forms
  File "easy_select2/forms.py", line 4, in <module>
    from django.utils.encoding import force_text
ImportError: cannot import name 'force_text' from 'django.utils.encoding' (django/utils/encoding.py)

We need to change force_text to force_str

No CI? Pull request welcome?

Hi!

I see no CI here — no Travis, no GitHub Actions, …. Would a pull request running tests using GitHub actions be welcome for review, in general?

Best, Sebastian

Use with django-storage.

Change
from django.templatetags.static import static
to
from django.contrib.staticfiles.storage import staticfiles_storage as static
in order for this to work with other static storages.

Easy select 2 breaks down admin with parler (or similar)

Easy select has hard-coded ModelForm class that uses for recreation of admin form.

select2_modelform method returns new model form, but it is always forms.ModelForm instance. But parler needs it's own TranslatableModelForm.

I think the easiest solution is to add additional argument for select2_modelform so it can return another instance. eg. form_model arg.

def select2_modelform(model, attrs=None, form_model=forms.ModelForm):
    classname = '%sForm' % model._meta.object_name
    meta = select2_modelform_meta(model, attrs=attrs)
    return type(classname, (form_model,), {'Meta': meta})

This way you can supply another form model class from admin and this can work with parler (or hvad) with little tweak:

select2_modelform(Poll, 
                   attrs={'width': '250px'}, 
                   form_model=parler.forms.TranslatableModelForm)

Select2 4.0.0

Just a heads up, we released Select2 4.0.0 last Sunday (about a week ago). It doesn't look like it would be too difficult to upgrade this project to support it as there isn't a lot of magic involved here.

change/edit url next to field does not get updated

Django version 1.11.13
django-easy-select2 1.3.4

In Django Admin:
If initially "item 1" is selected and I click the change/edit pencil-icon I get a popup to edit "item 1".
Selecting "item 2" and clicking the change/edit pencil-icon I still get a popup to edit "item 1".

Is this a bug, intended or an error on my part?

Inline relations: "Add another <Model>" breaks dropdown boxes

I have a model which has a relation to another model. This model has some fields, which use the Select2 dropdown singleselect boxes. When using the "Add another " link:
screen shot 2014-08-11 at 12 40 47
A new row is added to the table. However, when trying to select a value, the dropdown box doesn't "open".

This is the HTML of a working dropdown:

<td class="field-action_owner">
    <div class="select2-container" id="s2id_id_membership_set-6-action_owner" style="width: 250px;">
        <a href="javascript:void(0)" onclick="return false;" class="select2-choice" tabindex="-1">
            <span class="select2-chosen">[email protected]</span>
            <abbr class="select2-search-choice-close"></abbr>
            <span class="select2-arrow"><b></b></span>
        </a>
        <input class="select2-focusser select2-offscreen" type="text" id="s2id_autogen17">
    </div>
    <select name="membership_set-6-action_owner" id="id_membership_set-6-action_owner" tabindex="-1" class="select2-offscreen">
        <option value="">---------</option>
        <option value="1" selected="selected">[email protected]</option>
        <option value="2">[email protected]</option>
    </select>
    <script>
        $("#id_membership_set-6-action_owner").on('select2changed', function(e){
            $("#id_membership_set-6-action_owner").select2({"width": "250px"});
        }).trigger('select2changed');
    </script>
    <a href="/admin/auth/user/add/" class="add-another" id="add_id_membership_set-6-action_owner" onclick="return showAddAnotherPopup(this);"> <img src="/django/static/admin/img/icon_addlink.gif" width="10" height="10" alt="Add Another"></a>
</td>

This is the HTML of a faulty dropdownbox:

<td class="field-action_owner">
    <div class="select2-container" id="s2id_id_membership_set-7-action_owner" style="width: 250px;">
        <a href="javascript:void(0)" onclick="return false;" class="select2-choice" tabindex="-1">   
            <span class="select2-chosen">---------</span>
            <abbr class="select2-search-choice-close"></abbr>   
            <span class="select2-arrow"><b></b></span>
        </a>
        <input class="select2-focusser select2-offscreen" type="text" id="s2id_autogen19">
        <div class="select2-drop select2-display-none select2-with-searchbox">
            <div class="select2-search">
                <input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input">   
            </div>
            <ul class="select2-results"></ul>
        </div>
    </div>
    <select name="membership_set-7-action_owner" id="id_membership_set-7-action_owner" tabindex="-1" class="select2-offscreen">
        <option value="" selected="selected">---------</option>
        <option value="1">[email protected]</option>
        <option value="2">[email protected]</option>
    </select>
    <a href="/admin/auth/user/add/" class="add-another" id="add_id_membership_set-7-action_owner" onclick="return showAddAnotherPopup(this);"> <img src="/django/static/admin/img/icon_addlink.gif" width="10" height="10" alt="Add Another"></a>
</td>

The major difference I see is that the <script> tag is not loaded, which triggers the select2changed function.
In addition, the faulty dropdown also has a select2-drop div underneath the focusser.

Feature Request: "Tagging" (sorta)

I'd like to use django-easy-select2 to provide a "choice field" but where, if none of the choices are suitable, then the user can enter whatever he likes.

For example I have this code which works, but only as a normal choice field:

from django.contrib import admin
from django.forms.models import ModelForm
from adminsortable.admin import SortableAdmin
from easy_select2.widgets import Select2
from .models import VideoClip

class VideoClipAdminForm(ModelForm):
    class Meta:
        model = VideoClip

    def __init__(self, *args, **kwargs):
        super(VideoClipAdminForm, self).__init__(*args, **kwargs)

        def get_choices():
            values = VideoClip.objects.values_list('aspect_ratio', flat=True).distinct().order_by('aspect_ratio')
            return [(x, x) for x in values]

        self.fields['aspect_ratio'].widget = Select2(choices=get_choices())


class VideoClipAdmin(SortableAdmin, TimestampedAdmin):
    # form = select2_modelform(VideoClip, attrs={'width': '250px'})
    form = VideoClipAdminForm
    list_display = ('label', 'provider', 'clip_id', 'published', )
    list_editable = ('published', )

    fieldsets = (
        (None, {
            'fields': (
                'label',
                'published',
                'provider',
                'clip_id',
                'aspect_ratio',
                'longdesc',
            ),
        }),
    )

admin.site.register(VideoClip, VideoClipAdmin)

The purpose of all these gyrations is that I'd like the user to be able to enter their own 'aspect_ratio', but they can choose from the list of existing ones (determined by querying the same field on the same model).

I tried to provide a Select2 attribute of 'tags=get_choices()' instead of choices=get_choices(), but it didn't work.

Actually looks like perhaps it should be related to 'createSearchChoice' in Select2?

Is there a way to make this work?

How to handle the conflict in form?

easy-select2 is smart.

but as we declare the form in admin, it influence those form auto-generated by models like markdown field(comes from django_markdown)
which gave me js fault like:

image

so , how could I deal with multiple things in form?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.