Search code examples
javascriptpythondjangockeditordjango-ckeditor

Django-CKEditor Widget not loading dynamically


I am having problem on loading the second and next ckeditor widget on the front-end form in html. It works well in admin. When I click add more form set dynamically, the widget not come out but showing textarea instead, it just works on the first (initalized) form. I already follow the documentation step by step for basic requirements. I am using Django with django-ckeditor package. Got no javascript errors on the page.

Sorry for not showing any codes before. This is part of the javascript which dynamically adding another form set after button clicked:

<script src="//cdn.ckeditor.com/4.4.5/standard/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor-init.js"></script>

$('#add_more_work').click(function(){
var form_idx = $('#id_form_set-TOTAL_FORMS').val();
$('#form_set_work').append($('#empty_form_work').html().replace(/__prefix__/g, form_idx));
$('#id_form_set-TOTAL_FORMS').val(parseInt(form_idx) + 1);});

The field which use the ckeditor widget not loading after it added dynamically by this button but instead, it shows plain textarea. Did I miss anything?


Solution

  • You might want to look at using the formset:added and formset:removed JavaScript signals available from Django 1.9 onwards.

    A simple method (combined from django-content-editor and feincms3 ) might look like this:

    (function($) {
      $(document).on('formset:added', function newForm(event, row) {
        row.find('textarea').each(function() {
          CKEDITOR.replace(this.id);
        });
      });
    })(django.jQuery);
    

    I'll leave the handling of formset:removed to the reader.