Lijin
Lijin

Reputation: 151

How to use two ckeditor in same template in Django?

I am trying to develop a ckeditor comment box in Django. I successfully added the comment box. But now I am facing the issue in editing the comment part. What I am trying to do is when the user click on the edit button near to the comment, a modal popup appears and editing should happens there. The issue is the ckeditor is not showing in the modal. Instead of ckeditor a normal text field with data from the database is showing. In the console it showing "editor-element-conflict" error. Is there any solution for this?

Upvotes: 3

Views: 312

Answers (1)

Suoslex
Suoslex

Reputation: 41

I've figured out! It happens because you have a few ckeditor fields on the page, and they have the same ID, and CKEditor gets confused because it finds a few elements with the same ID. Solution: change IDs dynamically when the page is being generated.

I don't know the structure of your model, but I can assume that your form is defined like this:

class Comment(models.Model):
    text = models.TextField()

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = “__all__”

Then you need to change it like this:

from ckeditor.widgets import CKEditorWidget

class CommentForm(forms.ModelForm):
    base_textarea_id = "id_text"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.textarea_id_counter = 0
        self.fields['text'].widget = CKEditorWidget(attrs={'id': self.get_textarea_next_id})

    def get_textarea_next_id(self):
        result = self.base_textarea_id + str(self.textarea_id_counter)
        self.textarea_id_counter += 1
        return result

    class Meta:
        model = Comment
        fields = “__all__”

Of course, it’s based on very simplified model example, but I hope you’ve got the point.

Upvotes: 1

Related Questions