-
[Django] Quill Editor 적용하기Programming/Python 2023. 7. 6. 17:23
저같은 경우 Editor 하면 가장 먼저 떠오르는 것은 Ckeditor 이다.
그래서 Editor 가 필요한 경우에는 주로 Ckeditor를 사용하는데
이번에는 다른 Editor를 사용해볼려고 한다.
Quill
Quill - Your powerful rich text editor
Sailec Light Sofia Pro Slabo 27px Roboto Slab Inconsolata Ubuntu Mono Quill Rich Text Editor Quill is a free, open source WYSIWYG editor built for the modern web. With its modular architecture and expressive API, it is completely customizable to fit any ne
quilljs.com
Quill 이라는 에디터인데 나름 디자인도 깔끔하고 Star 도 36,000 개 정도를 받았다.
사실 이전에는 Ckeditor를 사용하고 있었는데 프론트에서 html 코드를 직접적으로 injection 하는 것이 별로인것 같아서 찾다가 발견한 것이 Quill Editor 이다.
그리고 거기에 더해 Quill 에디터에서 작성된 글을 보여줄 Next.js에서도 동일하게 뷰어를 사용할 수 있어서 좋은 선택지였다.
(내가 작성한 글과 동일한 스타일이 적용된다.)
그리고 여기에 도움을 주는 라이브러리가 있었는데
https://github.com/LeeHanYeong/django-quill-editor 이다.
GitHub - LeeHanYeong/django-quill-editor: django-quill-editor makes Quill.js easy to use on Django Forms and admin sites
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites - GitHub - LeeHanYeong/django-quill-editor: django-quill-editor makes Quill.js easy to use on Django Forms and admin s...
github.com
해당하는 라이브러리를 통해서 Ckeditor 와 같이 유사하게 작업을 할 수 있도록 도와준다.
적용하기
위의 라이브러리가 알려주는 방식으로 하면 문제없이 가능하다.
일단 나 같은 경우는 Django admin에서 글을 작성하고 해당 글을 Next.js 에서 렌더링하는 형식이기에 Admin에만 적용을 했다.
from django.db import models from django_quill.fields import QuillField from common.models import BaseModel from info.models import Tag, Attach # Create your models here. class Post(BaseModel): title = models.CharField("제목", max_length=100) content = QuillField("내용") tags = models.ManyToManyField(Tag, related_name="posts", through="post.PostTag") attach = models.ManyToManyField( Attach, related_name="posts", through="post.PostAttach" ) class Meta: ordering = ["-id"] db_table = "post" verbose_name = "게시판" verbose_name_plural = "게시판" def __str__(self): return self.title
이렇게 작성을 했다.
이렇게 하고 admin.py 는 평소에 작성하듯이 작성하면 아무 문제없이 동작한다.
Serializer
위에도 말했듯이 나의 경우에는 Django 내에서 content 를 보는 것이 아닌 Next.js에서 보는 것을 목표로 한다.
그러다보니 api 호출을 하면 해당하는 data가 읽기가 가능한 형태로 나와야 하는데 그렇지 않다.
일단 원래 코드를 보면 아래와 같이 작성되었다.
from rest_framework import serializers from django_quill.quill import QuillParseError from .models import Post from info.serializers import TagSerializer class PostSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, required=False) class Meta: model = Post fields = ("id", "content", "title", "tags", "attach", "created", "updated")
그렇다면 Response 는 어떻게 떨어지나?
{ "id": 2, "content": "<django_quill.fields.FieldQuill object at 0x103cfc880>", "title": "test", "tags": [], "attach": [], "created": "2023-07-06T10:57:57.999456+09:00", "updated": "2023-07-06T16:17:05.903683+09:00" }
아래와 같이 떨어진다. 그러면 우리가 원하는 content 를 렌더링이 불가능해진다.
그래서 해당하는 부분을 해결할 수 있는 방법을 아래의 링크에서 찾았다.
https://github.com/LeeHanYeong/django-quill-editor/issues/81
I can't get content of the object, but get this: <django_quill.fields.FieldQuill object at 0x000001A88692ACE0> · Issue #81 ·
I'm trying to access my Post model's content, which is QuillField(). in views.py I have: post_words = post.content But content's type is QuillField, so I get this <django_quill.fields.FieldQuill ob...
github.com
여기에서 serializermethodfield 를 가지고 해결을 하는 것을 알 수 있다.
그래서 나도 동일하게 코드를 작성했다.
from rest_framework import serializers from django_quill.quill import QuillParseError from .models import Post from info.serializers import TagSerializer class PostSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, required=False) content = serializers.SerializerMethodField() class Meta: model = Post fields = ("id", "content", "title", "tags", "attach", "created", "updated") def get_content(self, instance): try: return str(instance.content.html) except QuillParseError: return "해당 게시글은 Quill을 이용해 작성된 게시물이 아닙니다."
응답은 정상적으로 떨어졌고 해당하는 부분을 이용해서 원하는 형태로 렌더링이 가능했다.
주의할 점은 QuillParserError 가 뜨는 경우인데 return 값에도 설명되어있듯이 게시글이 quill로 작성이 되지 않은 경우에는
Parser 가 정상적으로 동작하지못해 error 를 발생한다.
그래서 나의 경우에는 아직 작성이 된 글이 없기에 별 상관이 없었지만 만약에 해당하는 부분이 고려가 되어진다면 마이그레이션을 거쳐야한다.
해당 글은https://django-quill-editor.readthedocs.io/en/latest/pages/migrating-to-quillfield.html
Migrating to QuillField — django-quill-editor 0.1 documentation
Migrating to QuillField To convert a field used as a TextField or CharField to a QuillField, the following operations are required. Suppose you had a model that looked like this. # Assuming this is the model you created in the posts app class NonQuillPost(
django-quill-editor.readthedocs.io
여기를 참고하면 된다.
'Programming > Python' 카테고리의 다른 글
[Bug] 동일한 이름을 가진 Library 가 꼬이는 경우 (0) 2023.06.16 Python 에서 환경변수(.env) 가져오기 (0) 2023.06.16 [Django] DRF Nested Router (0) 2023.06.13 [Django] Serializer HiddenField 활용 (0) 2023.06.13 [Django] Django Proxy Model 을 활용한 방법 (0) 2023.06.13