w
clone your own copy | download snapshot

Snapshots | iceberg

No images in this repository’s iceberg at this time

Inside this repository

serializers.py
text/x-python

Download raw (2.7 KB)

from django.contrib.auth.models import User
from .models import Attachment, Score
from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
from taggit_serializer.serializers import (TagListSerializerField,
                                           TaggitSerializer)
from guardian.shortcuts import assign_perm, get_users_with_perms, get_user_perms, remove_perm
from django.contrib.auth.models import User



class UserSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()

    class Meta:
        model = User
        fields = ['username', 'id']


class AttachmentSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()

    class Meta:
        model = Attachment
        fields = '__all__'
        # read_only_fields = ('attachment',)


class PermissionListSerializer(serializers.ListSerializer):
    def to_representation(self, obj):
        perms = get_users_with_perms(obj, attach_perms=True)
        return [{"username": k.username, "permissions": v} for k, v in perms.items()]

    def to_internal_value(self, data):
        print(data)
        # return data
        # I don't understand why I can't just return data
        return {"permissions": data}


class PermissionSerializer(serializers.Serializer):
    class Meta:
        list_serializer_class = PermissionListSerializer


class ScoreSerializer(TaggitSerializer, serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()
    tags = TagListSerializerField()
    permissions = PermissionSerializer(source="*", many=True)

    class Meta:
        model = Score
        fields = '__all__'

    def create(self, request, *args, **kwargs):
        instance = super().create(request, *args, **kwargs)
        assign_perm("view_score", request.user, instance)
        return instance

    def update(self, instance, validated_data):
        instance = super(ScoreSerializer, self).update(instance, validated_data)

        for user, perms in get_users_with_perms(instance, attach_perms=True).items():
            for perm in perms:
                remove_perm(perm, user, instance)

        for i in instance.permissions:
            user = User.objects.get(username=i.get('username'))
            perms = i.get('permissions')
            for perm in perms:
                assign_perm(perm, user, instance)

        return instance 


class ScoreLightSerializer(serializers.HyperlinkedModelSerializer):
    """A serializer exposing just a subsets of field when we don't need the full
    representation.
    """
    id = serializers.ReadOnlyField()
    tags = TagListSerializerField()

    class Meta:
        model = Score
        fields = ('id', 'title', 'tags', 'language', 'created_at', 'updated_at')