Skip to content

Commit

Permalink
Draft: CONTRIB => create attachments with tinymce (textfield) when ur…
Browse files Browse the repository at this point in the history
…l is present on the field
  • Loading branch information
juggler31 committed Aug 9, 2024
1 parent 98f6eda commit b22968f
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion geotrek/flatpages/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import re

from django.contrib import admin
from django.conf import settings
from django.utils.translation import gettext_lazy as _
Expand All @@ -6,7 +8,9 @@

from geotrek.flatpages import models as flatpages_models
from geotrek.flatpages.forms import FlatPageForm, MenuItemForm

from geotrek.flatpages.models import FlatPage
from geotrek.common.models import FileType, Attachment
from django.contrib.auth.models import User

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

def save_related(self, request, form, formsets, change):

# We override `ModelAdmin.save_related` to add/update/delete the attachment. Why not in
# `ModelAdmin.save_form` which may have looked like a better place? This is because Django's ModelAdmin
# does not commit the object in `save_form`, it waits for formsets' validations. We override
# `save_related` because we need the committed object (with an ID).
# See `django.contrib.admin.options.py:L1578`
super().save_related(request, form, formsets, change)
form.save_cover_image()
all_attachments = form.instance.attachments.all()
attachments_url = []
for field in form.instance._meta.get_fields():
if field.get_internal_type() == "TextField":
field_value = getattr(form.instance, field.name)
if field_value is not None:
matches = re.finditer(r'(src=\".+?/media/)(?P<url>.+?)\" ', field_value)
for match in matches:
if match["url"] not in all_attachments:
page = FlatPage.add_root(title="tinymceAttachment")
filetype = FileType.objects.get(type="Photographie")
attachment = Attachment.objects.create(

Check warning on line 85 in geotrek/flatpages/admin.py

View check run for this annotation

Codecov / codecov/patch

geotrek/flatpages/admin.py#L80-L85

Added lines #L80 - L85 were not covered by tests
content_object=page,
attachment_file=match["url"],
author='',
filetype=filetype,
creator=request.user,
)
form.instance.attachments.add(attachment)
attachments_url.append(match["url"])

Check warning on line 93 in geotrek/flatpages/admin.py

View check run for this annotation

Codecov / codecov/patch

geotrek/flatpages/admin.py#L92-L93

Added lines #L92 - L93 were not covered by tests

# print("Attachements_URL => ", attachments_url)
# print("Attachements => ", form.instance.attachments.all())


class MenuItemAdmin(BaseAdmin):
Expand Down

0 comments on commit b22968f

Please sign in to comment.