Home > Back-end >  Wagtail add RawHTMLBlock to field in model
Wagtail add RawHTMLBlock to field in model

Time:03-02

I'm trying to add field type as RawHTMLBlock in my model

I did

from wagtail.images.blocks import ImageChooserBlock
from wagtail.core import blocks
from wagtail.core.fields import RichTextField, StreamField
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel, StreamFieldPanel, FieldRowPanel, PageChooserPanel
from modelcluster.fields import ParentalKey
from wagtail.images.models import Image
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.images.widgets import AdminImageChooser

@register_snippet
class DefaultHeader(models.Model):
    
    title_html = models.CharField(max_length=100, null=True, blank=True)
    text_message = RichTextField(null=True, blank=True)
    code_text = blocks.RawHTMLBlock(null=True, blank=True)

    background = models.ForeignKey('wagtailimages.Image',
                                       related_name=' ',
                                       null=True,
                                       blank=True,
                                       verbose_name=_("Background"),
                                       on_delete=models.SET_NULL)

    panels = [
        FieldPanel("title_html"),
        FieldPanel("text_message"),
        FieldPanel("code_text"),
        ImageChooserPanel("background", classname="col12"),
    ]

All fields was add after makemigrations except for code_text that field wasn't add in my admin page I have title_html; text_message; background. but not code_text

CodePudding user response:

Blocks are not valid outside of StreamField. To achieve the same thing as RawHTMLBlock in a model field, define it as a TextField:

code_text = models.TextField(blank=True)

Then, when outputting it on a template, use Django's |safe filter to disable the HTML escaping that is applied as standard:

{{ header.code_text|safe }}
  • Related