class UserSerializer ReprSerializerMixin serializers ModelSerializer c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class UserSerializer(ReprSerializerMixin, serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'full_name', 'avatar_default', 'avatar_40', 'avatar_80',
'is_active')
full_name = serializers.CharField(source='get_full_name', read_only=True)
avatar_40 = serializers.SerializerMethodField()
avatar_default = serializers.SerializerMethodField()
avatar_80 = serializers.SerializerMethodField()
is_active = serializers.BooleanField(read_only=True)
def get_avatar_40(self, obj):
return obj.get_avatar_url(40)
def get_avatar_80(self, obj):
return obj.get_avatar_url(80)
def get_avatar_default(self, obj):
return obj.get_avatar_url(settings.AVATAR_DEFAULT_SIZE)
def validate_email(self, email):
email = User.objects.normalize_email(email)
existing = User.objects.all()
if self.instance:
existing = existing.exclude(id=self.instance.id)
existing = existing.filter(is_active=True, email__iexact=email)
if self.instance and self.instance.pk:
existing = existing.exclude(pk=self.instance.pk)
if existing.exists():
raise serializers.ValidationError("Email already taken by another user.")
return email