1

I'm working on a blog with Django, however my question is Python related not really Django related.

To write my blog posts I use Quill which generate the post in HTML. I save this HTML in the database than display the post using the filter |safe. Until now everything worked well until ... I want to display HTML code as examples which is obviously considered as safe because of the filter and is interpreted by the browser.

As a workaround I try to create a function able to escape HTML code as soon as they are between the tags but not escape the HTML out of this tag.

For example if quill return this:

<p> This is the code you need:
<pre class="myclass"> <div> The code </div> </pre>
</p>

I would like to save in database something like this:

<p> This is the code you need:
<pre class="myclass"> &lt;div&gt; The code &lt;/div&gt; </pre>
</p>

That way the safe tag will make the HTML code interpreted and display the HTML code inside the tag.

My problem is I don't find a way to make a replacement for each character only between the tags and keep everything as it is.

Basically I try to replace characters only in a substring of a string.

I'm running on python3.10

Any idea?

1 Answers1

-1

Possible duplicate of this

You can use either cgi.escape or html.escape

sudden_appearance
  • 1,968
  • 1
  • 4
  • 15
  • Please, spend some time reading ["How do I write a good answer?"](https://stackoverflow.com/help/how-to-answer). – accdias Feb 03 '22 at 12:30
  • @accdias, what's wrong? I attached the link to question with 2 well written answers and summed up the total here. I guess no need to rewrite same thing twice. – sudden_appearance Feb 03 '22 at 12:33
  • Read the article and judge by yourself. If you think it is a duplicate, flag the question as such and add a comment to the main thread. Posting an "answer" just to say that is not a good answer at all. – accdias Feb 03 '22 at 13:52