示例#1
0
class BoardSerializer(serializers.ModelSerializer):
    moderators = UserSerializer(many=True, read_only=True)
    admin = UserSerializer(read_only=True)
    
    class Meta:
        model = Board
        fields = (
            'title',
            'topic',
            'moderators',
            'admin'
        )

    def create(self, validated_data):
        user = self.context['request'].user

        assign_role(user, 'board_admin')

        return Board.objects.create(
            title=validated_data['title'],
            topic=validated_data['topic'],
            admin=user,
        )

    def save(self, request=None):
        return super().save()
示例#2
0
class JourneySerializer(serializers.HyperlinkedModelSerializer):

    user = UserSerializer()
    residence = ResidenceSerializer()
    campus = CampusSerializer()
    driver = UserSerializer()

    title = serializers.CharField(source="get_title", read_only=True)
    start = serializers.CharField(source="get_start", read_only=True)
    end = serializers.CharField(source="get_end", read_only=True)

    current_free_places = serializers.IntegerField()

    class Meta:
        model = Journey
        fields = [
            "id",
            "title",
            "kind",
            "free_places",
            "departure",
            "arrival",
            "start",
            "end",
            "disabled",
            "current_free_places",
            "user",
            "residence",
            "campus",
            "driver",
        ]
示例#3
0
class ReplySerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    agreed_num = serializers.SerializerMethodField()
    disagreed_num = serializers.SerializerMethodField()
    is_agreed = serializers.SerializerMethodField()
    is_disagreed = serializers.SerializerMethodField()

    class Meta:
        model = Reply
        fields = ('id', 'text', 'user', 'review', 'agreed_num',
                  'disagreed_num', 'is_agreed', 'is_disagreed', 'created_at')
        read_only_fields = ('id', 'created_at')

    def get_agreed_num(self, obj):
        return obj.agreed.all().count()

    def get_disagreed_num(self, obj):
        return obj.disagreed.all().count()

    def get_is_agreed(self, obj):
        user_id = self.context['request'].user.id
        return obj.agreed.filter(id=user_id).exists()

    def get_is_disagreed(self, obj):
        user_id = self.context['request'].user.id
        return obj.disagreed.filter(id=user_id).exists()

    def create(self, validated_data):
        user = self.context['request'].user
        return Reply.objects.create(user=user, **validated_data)
示例#4
0
class ClassVideoCommentSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)

    class Meta:
        model = ClassVideoComment
        fields = ["id", "content", "video", "author", "created", "modified"]
        read_only_fields = ["author", "video"]
示例#5
0
    def test_update(self):
        data = {
            "email": "*****@*****.**",
            "name": "string",
            "is_active": False
        }

        serializer = UserSerializer(data=data,
                                    context={"request": self.request},
                                    instance=self.user)
        self.assertTrue(serializer.is_valid())

        serializer.save()

        self.assertEqual(serializer.data.get("email"), data.get("email"))
        self.assertEqual(serializer.data.get("name"), data.get("name"))
        self.assertEqual(serializer.data.get("is_active"),
                         data.get("is_active"))
示例#6
0
 def to_representation(self, value):
     """Serialize tagged objects to a simple textual representation."""
     if isinstance(value, User):
         serializer = UserSerializer(value)
     elif isinstance(value, Journey):
         serializer = JourneySerializer(value)
     else:
         raise Exception('Unexpected type of tagged object')
     return serializer.data
示例#7
0
class ShiftSerializer(serializers.ModelSerializer):
    """Serializer for Shift objects."""

    assignees = UserSerializer(many=True)
    amount_of_orders = serializers.SerializerMethodField()
    max_user_orders = serializers.SerializerMethodField()

    def get_amount_of_orders(self, instance):
        """Get the amount of orders in the shift."""
        return instance.number_of_orders

    def get_max_user_orders(self, instance):
        """Get the max orders a user can still place in the shift."""
        return instance.user_max_order_amount(self.context["request"].user)

    def create(self, validated_data):
        """
        Create a Shift.

        Catch any ValueError exception that may be caused by the save() method of the Shift object.
        """
        try:
            super().create(validated_data)
        except ValueError as e:
            raise serializers.ValidationError(e)

    def update(self, instance, validated_data):
        """
        Update a Shift.

        Catch any ValueError exception that may be caused by the save() method of the Shift object.
        """
        try:
            return super().update(instance, validated_data)
        except ValueError as e:
            raise serializers.ValidationError(e)

    class Meta:
        """Meta class."""

        model = models.Shift
        fields = [
            "id",
            "venue",
            "start_date",
            "end_date",
            "can_order",
            "amount_of_orders",
            "max_orders_per_user",
            "max_orders_total",
            "max_user_orders",
            "assignees",
        ]
        read_only_fields = ["id", "amount_of_orders", "max_user_orders"]
示例#8
0
class CourseSerializer(serializers.ModelSerializer):
    participants = UserSerializer(many=True, read_only=True)

    def create(self, validated_data):
        course = super().create(validated_data)
        course.participants.add(self.context['request'].user)
        course.save()
        return course

    class Meta:
        model = Course
        fields = ('id', 'title', 'participants')
示例#9
0
class MessageSerializer(serializers.ModelSerializer):

    user = UserSerializer(read_only=True)
    journey = serializers.PrimaryKeyRelatedField(queryset=Journey.objects.all())

    class Meta:
        model = Message
        fields = ["id", "user", "journey", "content", "created"]

    @dispatch(MESSAGE)
    def save(self, **kwargs):
        return super(MessageSerializer, self).save(**kwargs)
示例#10
0
def jwt_payload_handler(user):
    username_field = get_username_field()
    username = get_username(user)
    payload = {
        'alpha': False,
        'exp': datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA,
        'user_id': "{}".format(user.id),
        'user': UserSerializer(user).data,
    }
    payload[username_field] = username
    if api_settings.JWT_ALLOW_REFRESH:
        payload['orig_iat'] = timegm(datetime.utcnow().utctimetuple())
    return payload
示例#11
0
class ClassVideoSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)

    class Meta:
        model = ClassVideo
        fields = [
            "id",
            "name",
            "description",
            "uploaded_class",
            "video",
            "author",
            "created",
            "modified",
        ]
        read_only_fields = ["author", "uploaded_class"]
示例#12
0
class ReviewDetailSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    reply = ReplySerializer(read_only=True)
    rating = serializers.ReadOnlyField()
    agreed_num = serializers.SerializerMethodField()
    disagreed_num = serializers.SerializerMethodField()
    is_agreed = serializers.SerializerMethodField()
    is_disagreed = serializers.SerializerMethodField()

    class Meta:
        model = Review
        fields = ('id', 'text', 'ethics', 'trust', 'accuracy', 'fairness',
                  'contribution', 'expertise', 'rating', 'reply', 'user',
                  'author', 'agreed_num', 'disagreed_num', 'is_agreed',
                  'is_disagreed', 'created_at')
        read_only_fields = ('id', 'created_at')

    def get_agreed_num(self, obj):
        return obj.agreed.all().count()

    def get_disagreed_num(self, obj):
        return obj.disagreed.all().count()

    def get_is_agreed(self, obj):
        user_id = self.context['request'].user.id
        return obj.agreed.filter(id=user_id).exists()

    def get_is_disagreed(self, obj):
        user_id = self.context['request'].user.id
        return obj.disagreed.filter(id=user_id).exists()

    def validate_user(self, user):
        author = self.context['request'].user
        if user == author:
            raise serializers.ValidationError('Cannot review yourself')

        if Review.objects.filter(author_id=author.id,
                                 user_id=user.id).exists():
            raise serializers.ValidationError('You have already reviewed')

        return user

    def create(self, validated_data):
        user = self.context['request'].user
        return Review.objects.create(author=user, **validated_data)
示例#13
0
class ThreadSerializer(serializers.ModelSerializer):
    admin = UserSerializer(read_only=True)
    
    class Meta:
        model = Thread
        fields = (
            'title',
            'board',
            'admin'
        )

    def create(self, validated_data):
        user = self.context['request'].user

        assign_role(user, 'thread_admin')

        return Thread.objects.create(
            title=validated_data['title'],
            board=validated_data['board'],
            admin=user,
        )

    def save(self, request=None):
        return super().save()
示例#14
0
    def to_representation(self, instance):
        data = super().to_representation(instance)
        data["days"] = WeekDaySerializer(instance.days.all(), many=True).data
        data["teacher"] = UserSerializer(instance.teacher.user).data

        return data
示例#15
0
class CommentSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Comment
        fields = ('id', 'user', 'text')
示例#16
0
class SolutionSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Solution
        fields = ('id', 'user', 'text')