asyncee / django-easy-select2

Select2 input widget for django selectable fields.
http://django-easy-select2.readthedocs.io/en/latest/
MIT License
214 stars 28 forks source link

Support passing themes? #71

Open hartwork opened 4 years ago

hartwork commented 4 years ago

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: https://github.com/asyncee/django-easy-select2/blob/0a87c501bc8fd7f3416efd07e72d6f50d14b235d/easy_select2/static/easy_select2/js/init.js#L3-L6

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

asyncee commented 4 years ago

I did not dig into code (it changed much from last time i touched it) but it looks like select2attrs constructor argument can help you out? https://github.com/asyncee/django-easy-select2/blob/master/easy_select2/widgets.py#L20

hartwork commented 4 years ago

Looks promising — let me try that and report back!

hartwork commented 4 years ago

Passing theme: 'classic' seems to work fine, I used:

# git --no-pager diff -- sampleproject/demoapp/admin.py
diff --git a/sampleproject/demoapp/admin.py b/sampleproject/demoapp/admin.py
index b756c91..a7ad382 100644
--- a/sampleproject/demoapp/admin.py
+++ b/sampleproject/demoapp/admin.py
@@ -6,7 +6,7 @@ from .models import Note, Category

 class NoteAdmin(admin.ModelAdmin):
-    form = select2_modelform(Note)
+    form = select2_modelform(Note, attrs={'theme': 'classic'})

 admin.site.register(Category)

However with theme boostrap4 I'll need to include another CSS file select2-bootstrap4.min.css everywhere I use django-easy-select2, e.g. even when used in the Django Admin. I was thinking of a way like this…

class Bootstrap4Select2Mixin(Select2Mixin):
    @property
    def media(self):
        return forms.Media(
            css=self.SELECT2_WIDGET_CSS + ['<some_path>/select2-bootstrap4.min.css'],
            js=self.SELECT2_WIDGET_JS
        )

…but I see no easy way to swap Select2Mixin with Bootstrap4Select2Mixin as a user without copy-modifying some of django-easy-select2's helper functions into the user project and keep that copy in sync. Am I missing some other way to do get additional CSS files in with less trouble?

gauravv7 commented 4 years ago

I ll put this as a PR, since this was not forseen as a proper requirement, so got left for this hard way reach.