簡體   English   中英

使用Django REST框架顯示Rich Text Uploading字段

[英]Using Django REST Framework to display Rich Text Uploading Field

我有一個在Python3上運行的Django應用程序,該應用程序設置了基本的博客應用程序。 在我的Post模型中,我對特定帖子的內容進行了以下設置。

from ckeditor_uploader.fields import RichTextUploadingField 

class Post(models.Model):
    content = RichTextUploadingField()

我還為Django設置了REST框架,以便當我對/api/posts/slug=abc-123進行GET請求時,它將運行以下命令:

class PostViewSet(viewsets.ViewSetMixin, generics.ListAPIView):
    """
    API endpoint that allows posts to be viewed.
    """
    serializer_class = PostSerializer 

    def get_queryset(self):
       queryset = Post.objects.all()
       # A bunch of Django filters
       return queryset

並會返回如下內容:

{
    "title" : "Abc 123",
    "slug" : "abc-123,
    "content" : "According to a survey, '93% of executives believe
                 that an employee’s style of dress at work 
                 influences his/her chance at a promotion&#39;.</p>\r\n\r\n<p>
                 This is more content blah blah blah."
}

(忽略JSON具有換行符的事實,即為了便於閱讀,假定它是格式正確的JSON文件)

如您所見,結果的content包含\\r\\n類的字符。 使用{{content | safe}} {{content | safe}} ,當Django呈現頁面時,效果很好,但我想在不使用Django作為后端的Web應用程序中顯示此數據。

長話短說,我需要一個javascript(或打字稿)庫,該庫將以Django使用其內置safe過濾器的方式呈現content的值。 注意它必須是獨立於Django的庫,只能在客戶端使用。

或者 ,我需要一種方法來存儲內容,該內容仍然允許Django中的RichTextUploadingField所有功能,並且不影響Django的呈現,但允許我以某種方式呈現HTML內容。

未經測試的代碼,您可以嘗試:

class PostSerializer(serializers.ModelSerializer):
    content = serializers.SerializerMethodField()

    def get_content(self, instance):
        from django.utils.safestring import mark_safe
        return mark_safe(instance.content)

    class Meta:
        model = Post
        fields = '__all__'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM