Home > Back-end >  Is there a switch to store the Wagtail RichTextBlock content to database in UTF-8?
Is there a switch to store the Wagtail RichTextBlock content to database in UTF-8?

Time:05-16

I am new in Django and Wagtail. I developed a website app using Django 4.0 and Wagtail 2.16.1. I found Django models.CharField by default stores content to database in UTF-8, while Wagtail RichTextBlock by default stores content to database in Unicode, which cause a problem when searching the East-Asian characters.

models.py

class BlogDetailPage(Page):
    custom_title = models.CharField('Title', max_length=60, help_text='文章标题')
    author = models.ForeignKey(User, on_delete=models.PROTECT)
    create_date = models.DateField("Create date", auto_now_add= True)
    update_date = models.DateField("Update date", auto_now=True)
    intro = models.CharField('Introduction', max_length=500, help_text='文章简介')
    tags = ClusterTaggableManager(through=BlogPageTag, blank=True)

    content = StreamField(
        [
            ('heading', blocks.CharBlock(form_classname="full title")),
            ('paragraph', blocks.RichTextBlock()),
            ('image', ImageChooserBlock()),
            ('blockquote', blocks.BlockQuoteBlock(label='Block Quote')),
            ('documentchooser', DocumentChooserBlock(label='Document Chooser')),
            ('url', blocks.URLBlock(label='URL')),
            ('embed', EmbedBlock(label='Embed')),
            #('snippetchooser', SnippetChooserBlock(label='Snippet Chooser')),
            ('rawhtml', blocks.RawHTMLBlock(label='Raw HTML')),
            ('table', TableBlock(label='Table')),
            ('markdown', MarkdownBlock(label='Markdown')),
            ('code', CodeBlock(label='Code')),
            ('imagedeck', CardBlock(label='Imagedeck')), 
            
        ],
        null=True,
        blank=True,
    )

search.py

def search(request):
    search_query = request.GET.get('query', None).strip()
    page_num = request.GET.get('page', 1)

    condition = None
    for word in search_query.split(' '):
        if condition is None:
            condition = Q(custom_title__icontains=word) | Q(intro__icontains=word) | Q(content__icontains=word.encode('utf-8'))
        else:
            condition = condition | Q(custom_title__icontains=word) | Q(intro__icontains=word) | Q(content__icontains=word.encode('utf-8'))

    search_results = []
    if condition is not None:
        search_results = BlogDetailPage.objects.live().filter(condition)

The problem is I can search English and Chinese in the intro field, but can only search English in content field. When checking the database (PostgreSQL UTF-8 by default), I found Intro field is in UTF-8 while content field is in Unicode. Wondering whether there is a setting to set the RichTextField store in UTF-8?

CodePudding user response:

Found some guy raised the same question several years ago. Wagtail default search not working with not english fields. The workaround to copy 2 fields just for searching index obviously is not an elegant solution. I used the thought of the second answer, i.e., to subclass StreamField and override get_prep_value.

models.py

class CustomStreamField(StreamField):
    def get_prep_value(self, value):
        if isinstance(value, blocks.StreamValue) and not(value) and value.raw_text is not None:
            # An empty StreamValue with a nonempty raw_text attribute should have that
            # raw_text attribute written back to the db. (This is probably only useful
            # for reverse migrations that convert StreamField data back into plain text
            # fields.)
            return value.raw_text
        else:
            return json.dumps(self.stream_block.get_prep_value(value), ensure_ascii=False, cls=DjangoJSONEncoder)

class BlogDetailPage(Page):
    template = "blog/blog_detail_page.html"    

    custom_title = models.CharField('Title', max_length=60, help_text='文章标题')
    author = models.ForeignKey(User,on_delete=models.PROTECT)
    create_date = models.DateField("Create date", auto_now_add= True)
    update_date = models.DateField("Update date", auto_now=True)
    intro = models.CharField('Introduction', max_length=500, help_text='文章简介')
    tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
    
    #categories = ParentalManyToManyField('blog.BlogCategory', blank=True)

    content = CustomStreamField(
        [
            ('heading', blocks.CharBlock(form_classname="full title")),
            ('paragraph', blocks.RichTextBlock()),
            ('image', ImageChooserBlock()),
            ('blockquote', blocks.BlockQuoteBlock(label='Block Quote')),
            ('documentchooser', DocumentChooserBlock(label='Document Chooser')),
            ('url', blocks.URLBlock(label='URL')),
            ('embed', EmbedBlock(label='Embed')),
            #('snippetchooser', SnippetChooserBlock(label='Snippet Chooser')),
            ('rawhtml', blocks.RawHTMLBlock(label='Raw HTML')),
            ('table', TableBlock(label='Table')),
            ('markdown', MarkdownBlock(label='Markdown')),
            ('code', CodeBlock(label='Code')),
            ('imagedeck', CardBlock(label='Imagedeck')), 

The new blog created will be stored in database in UTF-8. As for the existing blogs, just publish them again, the content will be changed from Unicode to UTF-8.

  • Related