[Django]-How do I use Django Dynamic Formset and Select2 together in the same page?

2👍

what worked for me is adding an on.click statement to call the select2 for the class .add-row after the formset script at the end of the document. Like this:

<script>
$( ".add-row" ).click(function() {
  $('.forselect2').select2();
});
</script>

Not sure if its still relevant for you just added in case someone also finds this. For your case, just replace ‘.forselect2’ with ‘select2’ and see if it works.

👤Greg

1👍

I can tell you from my personal experience that Django-Dynamic-Formset doesn’t behave well with other apps/tools on the same field. In some cases lots of alteration is needed to get it to work when other JS is present.

Take a look at this: (this one is using django_select2 and not select2)
https://github.com/anneFly/django-dynamic-formset-select2-poc

It hasn’t been updated for a while but you can see at the end it addresses some of the conflicts.

👤morinx

1👍

Just in case anyone else wants this, using inspiration from here, this solution worked for me using the standard JQuery, formset.js and select2, for n additional rows:

<script src='{% static "js/jquery.formset.js" %}'></script>
<script type="text/javascript">
    $('.formset_row-{{ formset.prefix }}').formset({
        addText: 'add another',
        deleteText: 'remove',
        prefix: '{{ formset.prefix }}',
        added: function($row) {
            $('#id_allowance-'+$row[0].rowIndex+'-accounts').select2({ width:'resolve'});
        }
    });
</script>

You will need to change the id concatenation function to match your own id pattern.

0👍

Use this code for django inline admin form

 <script type="text/javascript"> 

      django.jQuery(document).on('formset:added', function(event, $row, formsetName) { 
           if (formsetName == 'usereds_set'   ){
              $(".inline-related #id_"+$row.attr('id')+ "-eds" ).select2({ width:'resolve'});   
           } 
      });


 </script>

Note 1 : include select2 js/css in your body

Note 2: change formsetName condition in code

0👍

Done with SetTimeout(). Set select2() to all select components after 100ms of delay

0👍

I could get Django dynamic formsets to work finally after a good amount of debugging.

If the empty form is hidden (which will be the case) and you invoke select2 on empty forms, it doesn’t render properly. Try to invoke select2 only on visible select fields.

So, if your classname is multiselectbox, try to use something like this:

$('.multiselectbox:visible').select2();
👤Anupam

Leave a comment