serializers.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. from rest_framework import serializers
  2. from .models import CustomUser, InterestTag # 确保 InterestTag 也被导入
  3. from django.contrib.auth.password_validation import validate_password
  4. class InterestTagSerializer(serializers.ModelSerializer):
  5. class Meta:
  6. model = InterestTag
  7. fields = ('id', 'name', 'created_at')
  8. read_only_fields = ('id', 'created_at')
  9. class UserRegistrationSerializer(serializers.ModelSerializer):
  10. password = serializers.CharField(
  11. write_only=True,
  12. required=True,
  13. validators=[validate_password],
  14. style={'input_type': 'password'}
  15. )
  16. password2 = serializers.CharField(
  17. write_only=True,
  18. required=True,
  19. label="确认密码",
  20. style={'input_type': 'password'}
  21. )
  22. avatar = serializers.ImageField(required=False, allow_null=True, max_length=None, use_url=True)
  23. class Meta:
  24. model = CustomUser
  25. fields = ('email', 'phone_number', 'nickname', 'password', 'password2', 'school', 'bio', 'avatar')
  26. extra_kwargs = {
  27. 'nickname': {'required': True},
  28. 'school': {'required': False, 'allow_blank': True},
  29. 'bio': {'required': False, 'allow_blank': True},
  30. }
  31. def validate(self, attrs):
  32. if attrs['password'] != attrs['password2']:
  33. raise serializers.ValidationError({"password2": "两次输入的密码不匹配。"})
  34. return attrs
  35. def create(self, validated_data):
  36. validated_data.pop('password2')
  37. user = CustomUser.objects.create_user(**validated_data)
  38. return user
  39. class UserProfileSerializer(serializers.ModelSerializer):
  40. avatar_url = serializers.SerializerMethodField()
  41. interests = serializers.PrimaryKeyRelatedField(
  42. queryset=InterestTag.objects.all(),
  43. many=True,
  44. required=False,
  45. allow_empty=True
  46. )
  47. class Meta:
  48. model = CustomUser
  49. fields = (
  50. 'id', 'email', 'phone_number', 'nickname',
  51. 'avatar', 'avatar_url', 'bio', 'school',
  52. 'interests',
  53. 'date_joined', 'last_login', 'is_active'
  54. )
  55. read_only_fields = ('id', 'email', 'phone_number', 'date_joined', 'last_login', 'avatar_url')
  56. def get_avatar_url(self, obj):
  57. request = self.context.get('request')
  58. if obj.avatar and hasattr(obj.avatar, 'url'):
  59. if request is not None:
  60. return request.build_absolute_uri(obj.avatar.url)
  61. return obj.avatar.url
  62. return None
  63. class RecommendedUserSerializer(serializers.ModelSerializer): # 新增的序列化器
  64. """
  65. 用于推荐用户列表中显示用户信息的序列化器。
  66. """
  67. avatar_url = serializers.SerializerMethodField()
  68. common_interests_tags = InterestTagSerializer(many=True, read_only=True, source='common_interests_list') # 假设在视图中注入
  69. class Meta:
  70. model = CustomUser
  71. fields = (
  72. 'id',
  73. 'nickname',
  74. 'avatar_url',
  75. 'school',
  76. 'bio',
  77. 'common_interests_tags',
  78. )
  79. def get_avatar_url(self, obj):
  80. request = self.context.get('request')
  81. if obj.avatar and hasattr(obj.avatar, 'url'):
  82. if request is not None:
  83. return request.build_absolute_uri(obj.avatar.url)
  84. return obj.avatar.url
  85. return None
  86. def to_representation(self, instance):
  87. representation = super().to_representation(instance)
  88. bio = representation.get('bio')
  89. if bio and len(bio) > 50: # 截断bio到50字符
  90. representation['bio'] = bio[:50] + '...'
  91. return representation