Home > other >  CKEditor doesn't save data
CKEditor doesn't save data

Time:11-22

I'm using CKEditor for a form. In the admin it works fine, but when using it in the ModelForm of a CreateView the editor doesn't save data. As in the official docs, with this code:

class EventForm(forms.ModelForm):
    description = forms.CharField(widget=CKEditorWidget())
    image = forms.ImageField(widget=forms.ClearableFileInput(), required=False)
    class Meta:
        model = Event
        fields = ['title', 'description', 'type', 'start_date', 'end_date', 'fee']  

And this html:

<div>
    <form hx-post="{{ request.path }}" enctype="multipart/form-data" >
        {% csrf_token %}
        <div >
            <h1>Create new event</h1>
            <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div >
            {{form.media}}
            {{form.as_p}}
        </div>
        <div >
            <button type="button"  data-bs-dismiss="modal">Cancel</button>
            <input type="submit" value="Submit">
        </div>
    </form>
</div>

It won't let me submit the form as it will keep saying that the description field is required. Trying to add the CKEditor widget field in the init method, with this code:

class EventForm(forms.ModelForm):
    image = forms.ImageField(widget=forms.ClearableFileInput(), required=False)
    class Meta:
        model = Event
        fields = ['title', 'description', 'type', 'start_date', 'end_date', 'fee']  

    def __init__(self, *args, **kwargs):
        super(EventForm, self).__init__(*args, **kwargs)
        self.fields['start_date'].widget = forms.SelectDateWidget()
        self.fields['end_date'].widget = forms.SelectDateWidget()
        self.fields['description'].widget = CKEditorWidget()

The form will be sent, and the instance created. However, the 'description' field will be empty even if I enter some content. This is my view:

class CreateEvent(LoginRequiredMixin, CreateView):
    model = Event
    form_class = EventForm
    template_name = 'events/events_form.html'
    success_url = reverse_lazy('events:index')

    def form_valid(self, form):
        form.instance.author = self.request.user
        event_obj = form.save(commit=True)
        image = self.request.FILES.get('image')
        if image:
            EventImage.objects.create(title=event_obj.title, image=image, event=event_obj)
        return HttpResponse(status=204, headers={'HX-Trigger' : 'eventsListChanged'})

How should I make sure the data is being saved from the CKeditor?

CodePudding user response:

In models.py

from ckeditor.fields import RichTextField

In your model

description = RichTextField()

You don't need to do anything in the forms.py except putting it in the fields list

CodePudding user response:

You can use hx-vals to pass description value manually. Something like this should work:

hx-vals="js:{description: CKEDITOR.instances.id_description.getData()}"
  • Related