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
« 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"""
5from rest_framework import serializers
7from cloudinary.utils import cloudinary_url
9from src.accounts.models.user_photo import UserPhoto
12class PhotoSerializer(serializers.ModelSerializer):
13 """
14 Serializer for user photos.
16 Handles serialization of UserPhoto model instances, including a computed photo_url field.
17 """
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()
23 user = serializers.StringRelatedField(read_only=True)
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']
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]
46 return url
48 return None