Coverage for src/accounts/serializers/user_photo.py: 73%

15 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-08-04 12:59 +0300

1""" 

2This module defines the serializer for user photos. 

3""" 

4 

5from rest_framework import serializers 

6 

7from cloudinary.utils import cloudinary_url 

8 

9from src.accounts.models.user_photo import UserPhoto 

10 

11 

12class PhotoSerializer(serializers.ModelSerializer): 

13 """ 

14 Serializer for user photos. 

15 

16 Handles serialization of UserPhoto model instances, including a computed photo_url field. 

17 """ 

18 

19 # photo_url is a computed field, not stored in the model. 

20 # It returns the URL to the image hosted on Cloudinary. 

21 photo_url = serializers.SerializerMethodField() 

22 

23 user = serializers.StringRelatedField(read_only=True) 

24 

25 class Meta: 

26 model = UserPhoto 

27 # Include user, photo (the file), and photo_url (the URL for display) 

28 fields = [ 

29 'user', 

30 'photo', 

31 'photo_url', 

32 ] 

33 # user is read-only; it should not be set by the client 

34 read_only_fields = ['user'] 

35 

36 def get_photo_url(self, obj): 

37 """ 

38 Returns the URL to the uploaded photo using Cloudinary. 

39 This allows the frontend to display the image by URL. 

40 If no photo is present, returns None. 

41 """ 

42 if obj.photo: 

43 # cloudinary_url returns a tuple; [0] is the actual URL string 

44 url = cloudinary_url(obj.photo.public_id)[0] 

45 

46 return url 

47 

48 return None