Skip to content

Commit b22968f

Browse files
committed
Draft: CONTRIB => create attachments with tinymce (textfield) when url is present on the field
1 parent 98f6eda commit b22968f

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

geotrek/flatpages/admin.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import re
2+
13
from django.contrib import admin
24
from django.conf import settings
35
from django.utils.translation import gettext_lazy as _
@@ -6,7 +8,9 @@
68

79
from geotrek.flatpages import models as flatpages_models
810
from geotrek.flatpages.forms import FlatPageForm, MenuItemForm
9-
11+
from geotrek.flatpages.models import FlatPage
12+
from geotrek.common.models import FileType, Attachment
13+
from django.contrib.auth.models import User
1014

1115
if 'modeltranslation' in settings.INSTALLED_APPS:
1216
from modeltranslation.admin import TabbedTranslationAdmin
@@ -59,13 +63,37 @@ def get_form(self, request, *args, **kwargs):
5963
return form_class
6064

6165
def save_related(self, request, form, formsets, change):
66+
6267
# We override `ModelAdmin.save_related` to add/update/delete the attachment. Why not in
6368
# `ModelAdmin.save_form` which may have looked like a better place? This is because Django's ModelAdmin
6469
# does not commit the object in `save_form`, it waits for formsets' validations. We override
6570
# `save_related` because we need the committed object (with an ID).
6671
# See `django.contrib.admin.options.py:L1578`
6772
super().save_related(request, form, formsets, change)
6873
form.save_cover_image()
74+
all_attachments = form.instance.attachments.all()
75+
attachments_url = []
76+
for field in form.instance._meta.get_fields():
77+
if field.get_internal_type() == "TextField":
78+
field_value = getattr(form.instance, field.name)
79+
if field_value is not None:
80+
matches = re.finditer(r'(src=\".+?/media/)(?P<url>.+?)\" ', field_value)
81+
for match in matches:
82+
if match["url"] not in all_attachments:
83+
page = FlatPage.add_root(title="tinymceAttachment")
84+
filetype = FileType.objects.get(type="Photographie")
85+
attachment = Attachment.objects.create(
86+
content_object=page,
87+
attachment_file=match["url"],
88+
author='',
89+
filetype=filetype,
90+
creator=request.user,
91+
)
92+
form.instance.attachments.add(attachment)
93+
attachments_url.append(match["url"])
94+
95+
# print("Attachements_URL => ", attachments_url)
96+
# print("Attachements => ", form.instance.attachments.all())
6997

7098

7199
class MenuItemAdmin(BaseAdmin):

0 commit comments

Comments
 (0)