Skip to content

Commit

Permalink
(forum) wrap iframe in div tag, for display purpose
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentporte committed Apr 17, 2024
1 parent d5d52c2 commit 158ac51
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lacommunaute/forum/forms.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
import re

from django import forms

from lacommunaute.forum.models import Forum


def wrap_iframe_in_div_tag(text):
# iframe tags must be wrapped in a div tag to be displayed correctly
# add div tag if not present

iframe_regex = r"((<div>)?<iframe.*?</iframe>(</div>)?)"

for match, starts_with, ends_with in re.findall(iframe_regex, text, re.DOTALL):
if not starts_with and not ends_with:
text = text.replace(match, f"<div>{match}</div>")

return text


class ForumForm(forms.ModelForm):
name = forms.CharField(required=True, label="Titre")
short_description = forms.CharField(
Expand All @@ -15,6 +30,13 @@ class ForumForm(forms.ModelForm):
widget=forms.Textarea(attrs={"rows": 20}), required=False, label="Contenu (markdown autorisé)"
)

def save(self, commit=True):
forum = super().save(commit=False)
forum.description = wrap_iframe_in_div_tag(self.cleaned_data.get("description"))
if commit:
forum.save()
return forum

class Meta:
model = Forum
fields = ["name", "short_description", "description"]
39 changes: 39 additions & 0 deletions lacommunaute/forum/tests/tests_forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import pytest # noqa

from lacommunaute.forum.forms import wrap_iframe_in_div_tag

from lacommunaute.forum.forms import ForumForm
from lacommunaute.forum.models import Forum


def test_wrap_iframe_in_div_tag():
inputs = [
"<iframe src='xxx'></iframe>",
"<div><iframe src='yyy'></iframe></div>",
"<div><iframe src='zzz'></iframe>",
"<iframe src='www'></iframe></div>",
]
outputs = [
"<div><iframe src='xxx'></iframe></div>",
"<div><iframe src='yyy'></iframe></div>",
"<div><iframe src='zzz'></iframe>",
"<iframe src='www'></iframe></div>",
]
assert wrap_iframe_in_div_tag(" ".join(inputs)) == " ".join(outputs)


def test_saved_forum_description(db):
form = ForumForm(
data={
"name": "test",
"short_description": "test",
"description": "Text\n<iframe src='xxx'></iframe>\ntext\n<div><iframe src='yyy'></iframe></div>\nbye",
}
)
assert form.is_valid()
form.instance.type = Forum.FORUM_POST
forum = form.save()
assert forum.description.rendered == (
"<p>Text</p>\n\n<div><iframe src='xxx'></iframe></div>\n\n"
"<p>text</p>\n\n<div><iframe src='yyy'></iframe></div>\n\n<p>bye</p>"
)

0 comments on commit 158ac51

Please sign in to comment.