class AudioListSerializer(ModelSerializer): name = CharField(max_length=255, required=False) artist = ArtistSerializer(required=False) tags = TagListSerializer(many=True) extra_sm_image_thumbnail = ImageField(read_only=True) small_image_thumbnail = ImageField(read_only=True) has_lyrics = BooleanField(read_only=True) class Meta: model = Audio fields = [ 'id', 'name', 'length', 'has_lyrics', 'slug', 'bitrate', 'tags', 'playcount', 'small_image_thumbnail', 'audio_file', 'artist', 'extra_sm_image_thumbnail', 'created_date', ]
class ProfileImageSerializer(ModelSerializer): thumbnail = ImageField('thumbnail', ) image = ImageField() class Meta: model = ProfileImage read_only = 'thumbnail' fields = ['id', 'image', 'thumbnail']
class AudioDetailSerializer(ModelSerializer): artist = ArtistSerializer(required=False) album = AlbumSerializer(required=False) small_image_thumbnail = ImageField(read_only=True) extra_sm_image_thumbnail = ImageField(read_only=True) class Meta: model = Audio fields = ['id', 'name', 'album', 'audio_file', 'length', 'artist', 'extra_sm_image_thumbnail', 'small_image_thumbnail', 'lyrics']
class StudentSerializer(ModelSerializer): aadhaar_card_image = ImageField(required=True, max_length=None, use_url=True) student_image = ImageField(required=True, max_length=None, use_url=True) class Meta: model = Student fields = [ 'id', 'name', 'of_school', 'aadhaar_card_image', 'student_image' ]
class ImageSerializer(ModelSerializer): image_init = ImageField(required=True) image_end = ImageField(required=False) class Meta: model = ImageItems fields = "__all__" def update(self, instance, validated_data): for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() return instance
class UserSerializer(ModelSerializer): image = ImageField(source='user.profile.image', read_only=True) class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name', 'image')
class UserProfileDetailSerializer(ModelSerializer): user = SerializerMethodField() email = SerializerMethodField() picture = ImageField(use_url=True) class Meta: model = UserProfile fields = [ 'user', 'real_name', 'description', 'email', 'user_stu_id', 'school', 'picture', 'phone_number', ] def get_user(self, obj): return str(obj.user.username) def get_email(self, obj): return str(obj.user.email) def get_picture(self, obj): try: picture = obj.picture.url except: picture = None return picture
class CommentSerializer(ModelSerializer): reply_count = SerializerMethodField() replies = SerializerMethodField() username = CharField(source='user.username', read_only=True) user_image = ImageField( source='user.profile.image', read_only=True) class Meta: model = Comment fields = [ 'id', 'content_type', 'object_id', 'parent', 'comment', 'reply_count', 'replies', 'timestamp', 'username', 'user_image' ] def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0 def get_replies(self, obj): if obj.is_parent: return CommentChildSerializer(obj.children(), many=True).data return None
class UserPublicDetailSerializer(ModelSerializer): # username = ReadOnlyField() headimg = ImageField(default='moren.jpeg') bookNum = SerializerMethodField() uid = ReadOnlyField(source='id') fansNum = SerializerMethodField() followNum = SerializerMethodField() sex = SerializerMethodField() class Meta: model = LoginUser fields = ( 'headimg', 'uid', 'last_time', 'nickname', 'signature', 'sex', 'bookNum', 'fansNum', 'followNum', ) read_only_fields = ('last_time', ) def get_fansNum(self, obj): return obj.follows.all().count() def get_followNum(self, obj): return obj.fans.all().count() def get_bookNum(self, obj): return obj.books.all().count() def get_sex(self, obj): return obj.get_sex_display()
class FileSerializer(ModelSerializer): name = CharField(max_length=300) photo = ImageField(required=False) is_public = BooleanField(required=False) delete_date = DateField(required=False) # read_only pk = IntegerField(read_only=True) issue_date = DateTimeField(read_only=True) update_date = DateTimeField(read_only=True) file_user = DictField(read_only=True, source="user_as_dict") file_parents = ListField(read_only=True, source="parents_as_list") file_children = ListField(read_only=True, source="children_as_list") # A `HiddenField` does not take input from the user, or present any output fk_user = HiddenField(default=CurrentUserDefault()) class Meta: model = FileModel fields = ( "pk", "fk_parent", "name", "photo", "is_public", "issue_date", "update_date", "delete_date", "file_user", "file_parents", "file_children", "fk_user", )
class PublicUserSerializer(ModelSerializer, PhoneNumberSerializerMixin): """Defines a serializer for users that only keeps the minimum information.""" avatar = ImageField(read_only=True) email = EmailField(write_only=True) password = CharField(max_length=255, write_only=True) class Meta: """This Meta class defines the fields and models for the `PublicUserSerializer`.""" fields = ("id", "username", "email", "avatar", "password", "phone_number", "country") model = User def create(self, validated_data): """ Create a new user. :param validated_data: data to use for the creation of the user :return: the new user instance """ try: return User.objects.create_user(**validated_data) except IntegrityError as e: if "unique" in e.args[0].lower(): error = e.args[0].split(".")[-1].strip() if not error: # PSQL Format error = str(e.args).split("=")[0].split(" ")[-1].replace( "(", "").replace(")", "") raise ValidationError({ error: ["user with this {} already exists".format(error)] }) raise e
class ThumbnailImageSerializer(ModelSerializer): thumbnail = ImageField('thumbnail', ) class Meta: model = ThumbnailImage read_only = 'thumbnail' fields = ['id', 'image', 'thumbnail']
class RoleCreateSerializer(ModelSerializer): role_id = ReadOnlyField(source='id') id = IntegerField(source='player_id') first_name = ReadOnlyField(source='player.first_name') last_name = ReadOnlyField(source='player.last_name') img = ImageField(source='player.img', read_only=True) class Meta: model = Role fields = 'id', 'role', 'role_id', 'first_name', 'last_name', 'img' def to_representation(self, obj): data = super().to_representation(obj) request = self.context.get('request', None) if request and request.accepted_renderer.format == 'api': data['url'] = reverse('team-role-detail', (obj.team_id, obj.id), request=request) return data def create(self, validated_data): validated_data['team_id'] = self.context['view'].kwargs['team_pk'] try: return super().create(validated_data) except IntegrityError as e: raise RelationAlreadyExist(detail=e.args[0].split('DETAIL: ')[1])
class CustomRegisterSerializer(RegisterSerializer): # Inherit RegisterSerializer profile_pic = ImageField(required=False) def custom_signup(self, request, user): if self.validated_data.get('profile_pic', ''): user.profile_pic = self.validated_data.get('profile_pic', '') user.save(update_fields=['profile_pic', ])
class UserSerializerWithToken(ModelSerializer): token = SerializerMethodField(read_only=True) password = CharField(max_length=128, min_length=8, write_only=True) email = EmailField(write_only=True) username = CharField() name = CharField() avatar = ImageField(use_url=True, default='templates/deficon.png') @staticmethod def get_token(obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = LowUserModel fields = ('token', 'username', 'password', "email", "avatar", "name")
class CreatePollPostSerializer(ModelSerializer, CreatePostCommonFields): ques = CharField(allow_blank=True, error_messages={ 'required': 'ques key is required', 'blank': 'ques field is required' }) poll_end_value = CharField( error_messages={ 'required': 'poll_end_value key is required', 'blank': 'poll_end_value is required' }) poll_end_type = ChoiceField(choices=PollPost.POLL_END_TYPE, error_messages={ 'required': 'poll_end_type key is required', 'blank': 'poll_end_type is required' }) text_options = ListField( allow_empty=True, required=False, error_messages={'required': 'text_options key is required'}) image_options = ImageField( required=False, max_length=None, allow_empty_file=True, error_messages={'required': 'image_options key is required'}) class Meta: model = PollPost fields = [ 'about', 'description', 'is_18_plus', 'ques', 'poll_end_value', 'poll_end_type', 'text_options', 'image_options' ]
def from_native(self, data, files): # Validate any uploaded media media_field = ImageField(required=False) media_file = files.get('media', None) try: media = media_field.from_native(media_file) except ValidationError as err: if not hasattr(self, '_errors') or self._errors is None: self._errors = {} self._errors['media'] = list(err.messages) return # Attach uploaded media, if appropriate if media and 'media_url' not in data: data['media_url'] = Vision.upload_photo(media) return super(VisionSerializer, self).from_native(data, {})
class ProfilePictureSerializer(serializers.ModelSerializer): user_photo = ImageField(required=True) class Meta: model = Profile fields = ('user_photo', ) readonly_fields = ('user_photo', )
class ProfileSerializer(ModelSerializer): image = ImageField(allow_null=True, required=False, validators=['Check image']) class Meta: model = Profile fields = ('privacy', 'image')
class ArtistListSerializer(ModelSerializer): songs_count = IntegerField() name = CharField(max_length=255, required=False) small_image_thumbnail = ImageField(read_only=True) class Meta: model = Artist fields = ['id', 'name', 'slug', 'playcount', 'songs_count', 'small_image_thumbnail']
class SpotMainPicSerializer(serializers.ModelSerializer): main_pic = ImageField(required=True) class Meta: model = Spot fields = ('main_pic', ) readonly_fields = ('main_pic')
def from_native(self, data, files): # Validate any uploaded media media_field = ImageField(required=False) media_file = files.get('media', None) try: media = media_field.from_native(media_file) except ValidationError as err: if not hasattr(self, '_errors') or self._errors is None: self._errors = {} self._errors['media'] = list(err.messages) return # Attach uploaded media, if appropriate if media and 'media_url' not in data: data['media_url'] = Vision.upload_photo(media) return super(VisionSerializer, self).from_native(data, {})
class AccountSerializer(ModelSerializer): balance = MoneyField(default=Money('0.00', 'EUR'), read_only=True) avatar = ImageField(read_only=True) locked = BooleanField(read_only=True, source='is_locked') class Meta: model = mete_models.Account fields = ['avatar', 'balance', 'locked', 'created_at', 'updated_at']
class RecipeSerializer(serializers.ModelSerializer): """Serialize a recipe""" ingredients = serializers.PrimaryKeyRelatedField( many=True, queryset=Ingredient.objects.all()) tags = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all()) image = ImageField(allow_null=True, max_length=100, required=False, read_only=True) class Meta: model = Recipe fields = ( 'id', 'title', 'ingredients', 'tags', 'time_minutes', 'price', 'link', 'image', ) read_only_fields = ('id', ) @classmethod def setup_eager_loading(cls, queryset): """Perform necessary eager loading of data""" queryset = queryset.prefetch_related('tags', 'ingredients') return queryset def validate_tags(self, tags): error_tags_id = [ str(tag.id) for tag in tags if tag.user != self.context['request'].user ] if error_tags_id: error_tags_id_str = ','.join(error_tags_id) raise serializers.ValidationError( 'Its not allowed to use tags with id: {}, which are created by other user.' .format(error_tags_id_str)) return tags def validate_ingredients(self, ingredients): error_ingredients_id = [ str(ingredient.id) for ingredient in ingredients if ingredient.user != self.context['request'].user ] if error_ingredients_id: error_ingredients_id_str = ','.join(error_ingredients_id) raise serializers.ValidationError( 'Its not allowed to user ingredients with id: {}, which are created by other user' .format(error_ingredients_id_str)) return ingredients
class DishPhotoSerializer(DynamicFieldsModelSerializer): dish = PrimaryKeyRelatedField(queryset=Dish.objects.all()) image = ImageField(validators=[ FileExtensionValidator( ["jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "gif", "GIF"]) ]) class Meta: model = DishPhoto fields = ["id", "dish", "image"]
class PhotoSerializer(ModelSerializer): image = ImageField( use_url=True, allow_null=True, required=False, read_only=True, ) class Meta: model = Photo exclude = ["id"]
class ProductSerializer(ModelSerializer): image = ImageField() category_detail = CategorySerializer(source='category', read_only=True) class Meta: model = Product fields = '__all__' def get_image(self, product): request = self.context.get('request') image_url = product.image.url return request.build_absolute_uri(image_url)
class ImageSerializer(Serializer): image = ImageField() class Meta: Model = Image fields = '__all__' def create(self, validated_data): images_data = self.context['request'].FILES # print(images_data) test = Image.objects.create(image=images_data['image']) print('test : ', test) return test
class PostDetailSerializer(ModelSerializer): username = CharField(source='author.username', read_only=True) author_image = ImageField( source='author.profile.image', read_only=True) comments = SerializerMethodField() class Meta: model = Post fields = '__all__' def get_comments(self, obj): c_qs = Comment.objects.filter_by_instance(obj) comments = CommentSerializer(c_qs, many=True).data return comments
class SpeakerSerializer(ModelSerializer): code = CharField(source='user.code') name = CharField(source='user.name') avatar = ImageField(source='user.avatar') submissions = SerializerMethodField() @staticmethod def get_submissions(obj): talks = (obj.event.current_schedule.talks.all() if obj.event.current_schedule else []) return obj.user.submissions.filter( event=obj.event, slots__in=talks).values_list('code', flat=True) class Meta: model = SpeakerProfile fields = ('code', 'name', 'biography', 'submissions', 'avatar')
class CreateProfileSerializer(ModelSerializer): user_id = IntegerField() image = ImageField() def create(self, validated_data): profile = models.Profile.objects.create( user_id=validated_data['user_id'], location=validated_data['location'], sex=validated_data['sex'], date_of_birth=validated_data['date_of_birth'], image=validated_data['image'], ) return profile class Meta: model = models.Profile fields = ('user_id', ' location', 'sex', 'date_of_birth', 'image')