Skip to content

Commit

Permalink
🐛 Change for absolute url on trek's description in api v2
Browse files Browse the repository at this point in the history
  • Loading branch information
LePetitTim committed Jan 19, 2023
1 parent 7623264 commit 199254f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
4 changes: 4 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ In preparation for HD Views developments (PR #3298)
- Check pictogram exist on categories during generation of pdfs
- Fix ApidaeParsers does not update every time
- Add fixtures licenses initial install
<<<<<<< HEAD
- Fix default conf nginx for mobile
=======
- Replace image's relative URLs with absolute URLs in API v2 trek descriptions (#3321)
>>>>>>> 84e5d741b... :bug: Change for absolute url on trek's description in api v2


2.94.0 (2022-12-12)
Expand Down
5 changes: 4 additions & 1 deletion geotrek/api/tests/test_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,10 @@ def setUpTestData(cls):
reservation_system=cls.reservation_system,
practice=cls.practice,
difficulty=cls.difficulty,
accessibility_level=cls.accessibility_level
accessibility_level=cls.accessibility_level,
description='<p>Description</p>'
'<img src="/media/upload/steep_descent.svg" alt="Descent">'
'<img src="https://rando-millevaches-admin.fr/media/upload/pedestre.svg" alt="" width="1848" height="1848">'
)
cls.parent.accessibilities.add(cls.accessibility)
cls.parent.source.add(cls.source)
Expand Down
24 changes: 23 additions & 1 deletion geotrek/api/v2/serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from bs4 import BeautifulSoup
import json

from django.conf import settings
Expand Down Expand Up @@ -618,8 +619,29 @@ def get_published(self, obj):
def get_name(self, obj):
return get_translation_or_dict('name', self, obj)

def replace_src_absolute(self, data):
soup = BeautifulSoup(data, features="lxml")
imgs = soup.find_all('img')
for img in imgs:
if img.attrs['src'][0] == '/':
img['src'] = f'{self.context.get("request").build_absolute_uri("/")}{img.attrs["src"]}'

def get_description(self, obj):
return get_translation_or_dict('description', self, obj)
lang = self.context.get('request').GET.get('language', 'all') if self.context.get('request') else 'all'

if lang != 'all':
data = getattr(obj, '{}_{}'.format('description', lang))
if data:
self.replace_src_absolute(data)
else:
data = {}
for language in settings.MODELTRANSLATION_LANGUAGES:
data_lang = getattr(obj, '{}_{}'.format('description', language), )
if data_lang:
self.replace_src_absolute(data_lang)
data.update({language: data_lang})

return data

def get_access(self, obj):
return get_translation_or_dict('access', self, obj)
Expand Down

0 comments on commit 199254f

Please sign in to comment.