Skip to content
Snippets Groups Projects
serializers.py 1.42 KiB
Newer Older
  • Learn to ignore specific revisions
  • from rest_framework import serializers
    from common.serializers import CurrentUserProfileDefault
    from . import models
    
    from common.middleware import CurrentUserMiddleware
    
    Bodor Máté's avatar
    Bodor Máté committed
    _max_count = 1
    
    Bodor Máté's avatar
    Bodor Máté committed
    
    
    
    class DocumentSerializer(serializers.ModelSerializer):
        uploaded_by = serializers.HiddenField(default=CurrentUserProfileDefault())
    
        uploaded_by_name = serializers.SerializerMethodField()
    
    
        class Meta:
            model = models.Document
    
    Rafael László's avatar
    Rafael László committed
            fields = (
                'uploaded_by',
                'uploaded_at',
                'name',
                'description',
                'file',
                'uploaded_by_name',
                'solution',
            )
    
        def to_representation(self, instance):
            data = super().to_representation(instance)
    
    Rafael László's avatar
    Rafael László committed
            if not data['file']:
                data['file'] = ""
    
            return data
    
    
        def get_uploaded_by_name(self, obj):
            return obj.uploaded_by.full_name
    
    Bodor Máté's avatar
    Bodor Máté committed
        def validate_solution(self, value):
    
            profile = CurrentUserMiddleware.get_current_user_profile()
    
    Bodor Máté's avatar
    Bodor Máté committed
            if value not in profile.solution.all():
    
                raise serializers.ValidationError('You dont have permission!')
    
    Rafael László's avatar
    Rafael László committed
            count = models.Document.objects.filter(
                uploaded_by=profile, solution=value).count()
    
    Bodor Máté's avatar
    Bodor Máté committed
            if count >= _max_count:
    
    Rafael László's avatar
    Rafael László committed
                raise serializers.ValidationError(
                    'You cant upload more than ' +
                    str(_max_count) +
                    ' document to one solution!')
    
    Bodor Máté's avatar
    Bodor Máté committed
            return value