Как сохранить данные из CKEditor через Django Rest Framework с помощью javascript (ваниль)

Я пишу приложение, в котором есть функция добавления документа. По этой причине мне понадобился какой-нибудь текстовый редактор для форматирования документов.

Итак, вот views.py для рендеринга моего html:

def add_document_view(request):
    if request.user.is_authenticated:
        categories = Category.objects.all()
        languages = get_language_choices()
        context = {"allCategories":categories, "form":PostForm, "languages":languages}
        return render(request, "documents/add-document.html", context)
    return JsonResponse({"status":"500 Auth Error"})

add-document.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Document</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h1>Add Document</h1>
        <hr>
        <form method="POST" action="#">
            {% csrf_token %}
            <div class="form-group">
                <label for="title">Header:</label>
                <input type="text" class="form-control" id="header" name="header" placeholder="Enter document header" required>
            </div>
            <div class="form-group">
                <label for="category">Category:</label>
                <select class="form-control" id="category" name="category" required>
                    <option value="" disabled selected>Select category</option>
                    {% for category in allCategories %}
                    <option value="{{ category.id }}">{{ category.title }}</option>
                    {% endfor %}
                </select>
            </div>
            
            
            <div class="form-group">
                {{form.media}}  
                {{form.as_p}}
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>

    <script src="https://cdn.ckeditor.com/ckeditor5/38.0.0/classic/ckeditor.js" defer></script>
    
</body>
</html>

models.py


from django.db import models
from ckeditor.fields import RichTextField
from simple_history.models import HistoricalRecords
from .utils import get_language_choices

class Category(models.Model):
    title = models.CharField(max_length = 64, unique = True)

    def __str__(self):
        return self.title


class Document(models.Model):

    class DocumentStatus(models.TextChoices):
        ACTIVE = 'active', 'Active'
        ARCHIVED = 'archived', 'Archived'

    header = models.CharField(max_length = 32)
    body = RichTextField()
    category = models.ForeignKey(Category, on_delete = models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add = True)
    status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE)
    history = HistoricalRecords()

    def __str__(self):
        return self.header

forms.py для формы CKEditor:

from django import forms
from ckeditor.widgets import CKEditorWidget
from .models import Document

class PostForm(forms.Form):
    body = forms.CharField(widget = CKEditorWidget())
    class Meta:
        model = Document
        fields = ('body',)

script для получения моего API:

document.addEventListener("DOMContentLoaded", ()=>{
    const richTextContent = CKEDITOR.instances[0].getData(); 
    // How do i get the content and sanitize it in order to pass it to my API
    // with url "/api/" POST request

})

Итак, главный вопрос: Как мне получить содержимое формы ckeditor, чтобы отправить его в мой API?

Вернуться на верх