django CKEditor不保存数据

uurity8g  于 2022-11-26  发布在  Go
关注(0)|答案(2)|浏览(206)

我在一个表单中使用CKEditor。在admin中它工作正常,但是当在CreateView的ModelForm中使用它时,编辑器不保存数据。和在官方文档中一样,使用以下代码:

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']

还有这个html:

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

它不让我提交表单,因为它会一直说描述字段是必需的。尝试在init方法中添加CKEditor小部件字段,使用以下代码:

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()

表单将被发送,示例将被创建。但是,即使我输入一些内容,“描述”字段也将为空。这是我的视图:

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'})

我应该如何确保数据是从CKeditor保存的?

ogq8wdun

ogq8wdun1#

在models.py

from ckeditor.fields import RichTextField

在您的模型中

description = RichTextField()

您无需在www.example.com中执行任何操作forms.py,只需将其放入字段列表即可

kadbb459

kadbb4592#

您可以使用hx-vals来手动传递描述值。

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

相关问题