Skip to content

Commit

Permalink
patch: add request object to the context (#1068)
Browse files Browse the repository at this point in the history
* patch: add request object to the context

* patch: use request.build absolute uri
  • Loading branch information
tinashechiraya authored Aug 14, 2024
1 parent dde4ad5 commit cae8d2d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
18 changes: 8 additions & 10 deletions django_project/monitor/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@
ObservationPestImage,
Sites,
SiteImage,
Assessment,
Pest
Assessment
)
from django.contrib.sites.models import Site


class ObservationsAllFieldsSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -216,13 +214,13 @@ def get_collector_name(self, obj):

def get_images(self, obj: Observations):
"""Return images of observation with full URL paths."""
domain = Site.objects.get_current().domain
request = self.context.get('request')
images = obj.observationpestimage_set.all().order_by('pest__name', '-id')
serialized_images = ObservationPestImageSerializer(images, many=True).data

for image in serialized_images:
if 'image' in image:
image['image'] = f'https://{domain}{image["image"]}'
if 'image' in image and request:
image['image'] = request.build_absolute_uri(image['image'])

return serialized_images

Expand All @@ -244,13 +242,13 @@ class SitesAndObservationsSerializer(serializers.ModelSerializer):

def get_images(self, obj: Sites):
"""Return images of site with full URL paths."""
domain = Site.objects.get_current().domain
request = self.context.get('request')
images = obj.siteimage_set.all()
serialized_images = SiteImageSerializer(images, many=True).data

for image in serialized_images:
if 'image' in image:
image['image'] = f'https://{domain}{image["image"]}'
if 'image' in image and request:
image['image'] = request.build_absolute_uri(image['image'])

return serialized_images

Expand All @@ -268,7 +266,7 @@ class Meta:

def get_observations(self, obj):
observations = Observations.objects.filter(site=obj).order_by('-obs_date', '-gid')
return ObservationsDataOnlySerializer(observations, many=True).data
return ObservationsDataOnlySerializer(observations, many=True, context=self.context).data

def to_representation(self, instance):
data = super().to_representation(instance)
Expand Down
2 changes: 1 addition & 1 deletion django_project/monitor/site_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,5 +211,5 @@ def get(self, request):
else:
sites = Sites.objects.all()

serializer = self.serializer_class(sites, many=True)
serializer = self.serializer_class(sites, many=True, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)

0 comments on commit cae8d2d

Please sign in to comment.