Meera Joseph
Meera Joseph

Reputation: 5

Issue with Internal Links in Wagtail RichTextEditor

I'm using the Wagtail RichTextEditor, which has an option to add links. Using this link option, I can upload both internal and external links. When I add an external link, it works fine. However, when I try to add an internal link and publish the page, the link appears with a broken link symbol. Additionally, in the API, the href attribute is showing as None. Has anyone encountered this issue before? How can I resolve it?

My code is like this:

class CustomizeRichTextBlock(RichTextBlock):
    def __init__(self, **kwargs):
        super().__init__(features=[
            'h1', 'h2', 'h3', 'h4', 'h5', 'bold', 'italic', 'ol', 'ul', 'hr', 
            'link', 'image', 'blockquote', 'mark', 'embed', 'code', 'superscript', 
            'subscript', 'strikethrough','text-alignment','underline'
        ], **kwargs)

    def add_link_style(self, html_content):
        # Add the `style` attribute to all <a> tags
        styled_content = re.sub(r'<a ', r'<a style="color: #2FC1D4;" ', html_content)
        return styled_content    
        

    def get_api_representation(self, value, context=None) -> str:
        # Generate the initial HTML content from rich text
        html_content = expand_db_html(value.source)
        
        # Add custom link styling
        styled_content = self.add_link_style(html_content)

         # Replace empty paragraphs with a unique placeholder for line breaks
        styled_content = re.sub(r'<p[^>]*>\s*</p>',r'<p><br /></p>', styled_content)

        # Return the final content
        return styled_content
     

Upvotes: 0

Views: 49

Answers (1)

gasman
gasman

Reputation: 25227

This would happen if you have no site records set up under Settings -> Sites, or the page you're linking to exists somewhere in the page tree that isn't covered by any site records.

If you have a site structure like

Home
|
|- Blog
|  |- First blog post
|  |- Second blog post
|
|- People
   |- Alice
   |- Bob

then there needs to be a site record with a root page of 'Home'. This serves two purposes:

  1. When a request comes in for a URL like /people/alice/, it provides the starting point for locating that page - look for a child named 'people', then 'alice'
  2. When outputting the URL of a given page, the path is computed relative to that root page - so it's /people/alice/ rather than /alice/ or /home/people/alice/

Since you're working with get_api_representation, you're probably building a 'headless' site where Wagtail isn't responsible for serving the pages, so point 1 doesn't apply - but you're still relying on Wagtail to return the URLs to linked pages, so you still need the site record for point 2.

Upvotes: 1

Related Questions