【问题标题】:Wagtail - Change image tags/format in Rich Text EditorWagtail - 在富文本编辑器中更改图像标签/格式
【发布时间】:2016-07-27 09:02:58
【问题描述】:

我正在使用没有模板的 wagtail(我使用 rest-framework 构建了一个 API)。 我想在富文本编辑器中更改图像的格式

例如,这是我现在的 RichText 字段:

<p>test test test</p>
<p><br/></p><p><embed alt=\"IMG_1232.jpg\" embedtype=\"image\" format=\"test\" id=\"4\"/><br/></p>"

相反,我希望它只包含图像的直接链接,甚至更好地包含我定义的过滤器(使用 register_image_format)的图像。 例如:

<p>test test test</p>
<p><br/></p><p><embed href="/media/IMG_1232.width-400"/><br/></p>"

有可能吗? 我查看了 hallo.js,但不确定如何处理它......

谢谢

【问题讨论】:

    标签: django wagtail hallo-js


    【解决方案1】:

    向您的模型添加一个方法,该方法返回在富文本字段上调用richtext 过滤器的结果。然后,您可以使用此方法代替 api_fields 定义中的字段本身:

    from wagtail.core.templatetags import wagtailcore_tags
    
    def MyPage(Page):
        body = RichTextField()
    
        def rendered_body(self):
            return wagtailcore_tags.richtext(self.body)
    
        api_fields = [
            APIField('rendered_body'),
        ]
    

    【讨论】:

      【解决方案2】:

      要获取图像、嵌入和文档的完整 URL,您必须通过富文本 filter 模板标签运行富文本块的内容。

      from wagtail.wagtailcore.templatetags import wagtailcore_tags
      
      rich_text = wagtailcore_tags.richtext(rich_text_source)
      

      rich_text 应该已经嵌入和带有完整 URL 的图像。

      如果你在序列化器中使用 DRF,它看起来像这样

      from django.contrib.auth.models import User
      from django.utils.timezone import now
      from rest_framework import serializers
      from wagtail.wagtailcore.templatetags import wagtailcore_tags
      
      class SomeSerializer(serializers.Serializer):
          rich_text = serializers.SerializerMethodField()
      
          def get_rich_text(self, obj):
              return wagtailcore_tags.richtext(obj.rich_text.source)
      

      【讨论】:

      • 我没有使用模板(我正在使用 DRF)。我现在正在使用流字段。你知道这是否可能吗?谢谢
      • 这就是我上面提到的方式,只需将 html 源代码传递给 wagtailcore_tags.richtext 函数。它将为您扩展 URL
      • 图像不在 RichText 中,而是在 ImageChooserBlock 中。我不确定这是否可能,并且我必须为每个图像访问数据库两次——一次从其 ID 中获取图像对象,另一次获取 image_rendition。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多