在Django中使用Quill编辑器进行表单输入,

k10s72fa  于 2023-05-19  发布在  Go
关注(0)|答案(2)|浏览(185)

我想在Django中的表单输入上使用Quill编辑器。
从Quill playground中的例子中,我看到容器总是div
我如何让它用<textarea>代替div,以及文本保留在textarea中,以便在我通过Django提交表单时工作;
我知道有一个django-quill包,但最后一次提交是在2015年完成的,据报道不适用于新的Django版本,除了我想做更多的定制。

jvlzgdj9

jvlzgdj91#

Quill正在contenteditable div中工作。如果你想让它“看起来像”一个文本区域,使用css应该很容易。
但如果你使用的是Quill,这可能是使用富文本,如粗体、斜体、项目符号……而丰富的内容不能存在于只处理纯文本(没有文本格式)的textarea中。这就是为什么它必须留在contenteditabediv中。
你的表单应该在提交时,寻找这个div内容,并以html格式将其发送到你的后端(要么用纯js,要么这次将html内容复制粘贴到一个隐藏的文本区域中)。

y1aodyip

y1aodyip2#

这是基于https://stackoverflow.com/a/65096360。它使用Bootstrap 5类来使div看起来像一个文本区域。

<form method="post">
    {% csrf_token %}

    {{post_form|crispy}}
    <label for="quill_editor" class="form-label requiredField">
      Body<span class="asteriskField">*</span>
    </label>
    <div id="quill_editor" class="textarea form-control"></div>

    <button type="submit" class="btn btn-primary mt-2">
      Submit
    </button>
</form>

{% load static %}
<script src="{% static 'js/vendor/quill.1.3.7.min.js' %}"></script>
<script>
  const quill = new Quill('#quill_editor', {theme: 'snow'});
  const bodyField = document.getElementById('id_body');

  // Update the body input field as it changes. I tried to do this on form submit, but the browser's input validation runs before the form is submitted. If there's no value in there, input validation fails.
    quill.on('text-change', () => {
      bodyField.value = quill.root.innerHTML;
    });
</script>

我用CSS隐藏了post_form创建的原始textarea容器:#div_id_body {display: none}body是模型中的名称。你的名字可能不一样。

相关问题