The django-ckeditor modal form is not updating data upon submission

I am working on a django project that utilizes django-ckeditor. I am using HTMX to create a bootstrap modal for displaying my edit form. The form renders correctly, especially after adding the ckeditor.js files at the end of the body in base.html. However, when I open the form in a modal and click save, the form.has_changed() method returns false. It seems like the POST request does not include the changed value for the CKEditor field.

Here is a simplified version of my code:

My model:

class MyModel(models.Model):    
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=150)
    comment = RichTextField(blank=True, null=True)

    def __str__(self):
        return f'{self.name} - {self.description}'

My form:

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = (
            'name',
            'description',
            'comment',
        )

My View:

def update_data(request, pk):
    model = MyModel.objects.get(id=pk)
    form = MyForm(request.POST or None, instance=model)

    if request.method == "POST":
        if form.is_valid():
            print(form.has_changed())
            form.save()
            return redirect("detail-form", pk=model.id)

Advice needed: When I load the editor after the page has already loaded, the saved changes are not reflected in the POST request. Any suggestions on how to resolve this issue?

Answer №1

The issue did not lie with the modal code itself, but rather with HTMX causing the problem. This seems to be a common problem when utilizing HTMX with RTF editors, and I believe the solution provided here could be effective in most cases. A similar issue was encountered with tinyMCE, and a resolution for that can be found here. Below is my implementation using CKEditor:

<div id="modal-backdrop" class="modal-backdrop fade show" 
style="display:block;">    </div>
<div id="modal" class="modal fade show" tabindex="-1" style="display:block;">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-body">
            <form method="post">
                {% csrf_token %}
    
                {{ form.media }}

                <script>
                    document.body.addEventListener('htmx:configRequest', (event) => {
                        var element = new CKEDITOR.dom.element( document.getElementById( '{{ form.comment.id_for_label }}' ) );
                        event.detail.parameters['{{ form.comment.html_name }}'] = element.getEditor().getData();        
                    })
                </script>
                {{ form.as_p|safe }}
                <button type="submit" hx-post="{% url 'update-data' entry.id %}" hx-target="#entryform_{{entry.id}}" hx-swap="outerHTML"
                    class="btn btn-primary" onclick="closeModal()">
                    Submit
                </button>
            </form>
        </div>
      </div>
    </div>
  </div>

Although it may not be the most ideal placement for the script, it functions well in this location. Additionally, this location allows for greater flexibility and generality by utilizing form tags.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transmitting information via Ajax, jquery, Node.js, and Express

Seeking assistance as I struggle to comprehend the process while trying to implement it based on various online resources. My carousel directs users right after signing up, and I aim to gather information about their profile through simple input questions. ...

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...

refreshing the webpage with information from an API request

I am completely new to web development, so please bear with me. I am attempting to make a simple API call: const getWorldTotal = async () => { const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/cov ...

Is it possible to eliminate the css class prefix when using Modular css in React?

When working with React & NextJS, I have observed that my modular SCSS files are automatically prefixing my classnames with the name of the file. Is there a way to turn off this feature as it is making the DOM structure difficult to interpret? For instanc ...

You may encounter the issue of receiving a message stating "Origin is not allowed by Access-Control-Allow-Origin" while utilizing Django authentication on a specific URL

I'm encountering CORS issues with Django and React (fetch). Here's how Django is configured: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "dja ...

The response to ajax requests does not appear in Chrome Dev Tools

I'm experiencing an issue with my nodejs application where I encounter a peculiar situation when making ajax requests using jQuery. When I make a redirection in the callback function of the AJAX request, the response in the developer tools appears emp ...

Populate the auto complete input box with items from a JSON encoded array

I have a PHP file that returns a JSON encoded array. I want to display the items from this JSON array in an autocomplete search box. In my search3.php file, I have the following code: <?php include 'db_connect.php'; $link = mysqli_connect($ho ...

Using Ajax and jQuery to fetch information from a previous search query

I'm currently utilizing Ajax and jQuery for my chat feature. Some may find it overly complex, but as long as it works, that's all that matters. It's functioning properly on the first friend result, however, not on the others. The issue lies ...

Navigating in a Curved Path using Webkit Transition

Currently, I am working on a simple project to learn and then incorporate it into a larger project. I have a basic box that I want to move from one position to another using CSS webkit animations and the translate function for iOS hardware acceleration. I ...

The program is designed to only allow up to two images to be wrapped

I'm struggling with a short jQuery program that I need help with. The problem is, I can't seem to get it to wrap more than two images in the same row. My goal is to create a website that side-scrolls, and I thought this approach would be the simp ...

Switching the vertical alignment of grid items in Material UI when the page is collapsed

When the page is collapsed, the Left grid item element moves to the top of the page and the Right grid element is positioned below it. I would like to reverse this behavior so that the Right element appears on top and the Left element below when the page ...

Can native types in JavaScript have getters set on them?

I've been attempting to create a getter for a built-in String object in JavaScript but I can't seem to make it function properly. Is this actually doable? var text = "bar"; text.__defineGetter__("length", function() { return 3; }); (I need th ...

Solutions for resolving the error "Unable to access property 'value1' because it is undefined"

constructor() { super(); this.state = { value1 : Math.floor(Math.random() * 100), value2 : Math.floor(Math.random() * 100), value3 : Math.floor(Math.random() * 100), proposedAnswer : Math.floor(Math.random() * 3) + this.state.value1 + t ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

Ways to retrieve the complete user object in passport

Recently, I've been diving into utilizing Express authentication with Passport and React for the frontend. While working on this project, a question came up: How can I access the entire authenticated user object? This is what my database model looks l ...

CSS animation stalling

While my angular app is loading all the necessary content through ajax, I display a loader on top of the content on a darker layer. The SVG used in this process contains an animateTransform: <svg width="38" height="38" viewBox="0 0 38 38" xmlns="http: ...

Error encountered when using Firefox with Django due to CSRF token issue

After implementing some advanced error checking in a form that went beyond the capabilities of celery, everything was running smoothly until a colleague discovered that the form was no longer functional on Firefox (as it had been developed and tested on Ch ...

Having trouble creating an embed: The property 'MessageEmbed' is undefined

I recently built a Discord bot that has the functionality to ban members. However, I am facing an issue where I am unable to respond with a message embed after banning someone. Despite having discord.js updated to version 12, I can only send a normal messa ...

Is the JavaScript Date object consistently displayed in the America/New_York timezone?

The server sends me a time-stamp in milliseconds (Unix time / time from Epoch) with the constant timezone "America/New_York". On my client side, I want to ensure that the time is displayed according to the America/New_York timezone. I have been using Joda- ...

Guide to linking audio to MediaStream using Three.JS AudioContext

I have a MediaStream created from a canvas and I am trying to add audio to it from the Three.js audio stream. After attempting various methods, I found that the most concise solution is shown in the code snippet below. The stream seems to be added success ...