applegrew / django-select2

This is a Django integration for Select2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it possible to remove the file "django_select2.js" from form rendering?

dan-developer opened this issue · comments

Goal
Is it possible to remove the file "django_select2.js" from form rendering?

Problem
That would be good for loading via AJAX. For example, a modal. Every time it loads, it reloads the file and calls.

https://github.com/applegrew/django-select2/blob/master/django_select2/static/django_select2/django_select2.js#L65

Code Snippet
This is the result of django select2 modal loading

<input type='hidden' name='csrfmiddlewaretoken' value='NEBrcXQxXtTe86Fr5KeQ5dJG6hynovKqjEasqGf63WBzrB0ItPDjyW6caJIZ2ong' />
<script type="text/javascript" src="/static/django_select2/django_select2.js"></script>

Hi @AndersonDan

Thanks for reaching out and yes, what you are trying is possible. I wrote a little example that should work, but I haven't tested the code.

Python Part:

class MyWidget(ModelSelect2Widget):
    def build_attrs(self, *args, **kwargs):
        attrs = super().build_attrs(*args, **kwargs)
        attrs['class'] = attrs['class'].replace('django-select2', 'my-widget', 1)
        return attrs

    @property
    def media(self):
        return forms.Media(
            js=ModelSelect2Widget.media.js + ('myapp/js/my_widget.js',),
            css=ModelSelect2Widget.media.css,
        )

JS part

(function ($) {
    function initCallback($element) {
        const settings = {
            // Whatever you want to change :)
        };
        $element.djangoSelect2(settings);
    }
  initCallback($('.my-widget'));
})(window.jQuery)

I hope that helps you a bit. Let me know if you have further questions.

Best
-Joe

Continue loading script while rendering form (crispy).

<input type='hidden' name='csrfmiddlewaretoken' value='WspM3vTN0HspKk2avxtCXqMmXTJsTOVJRsD9YBWMIOd7yODjeskJlbaSETlcUCVy' /> <script type="text/javascript" src="/static/django_select2/django_select2.js"></script> <div>

My intention is that no script is loaded apart from the widget, and yes, I will load in the base template, both the select2 script, css select2, and django_select2.js. Thus avoiding things like "jQuery is not defined".

Thanks for the receptiveness.

Dear @dan-developer , had the same (?) issue with crispy forms and found the the crispy helper attribute include_media to not inject media css/js in the crispy form:

include_media: Whether to automatically include form media. Set to False if you want to manually include form media outside the form. Defaults to True.

(https://django-crispy-forms.readthedocs.io/en/latest/api_helpers.html)