clone your own copy | download snapshot

Snapshots | iceberg

No images in this repository’s iceberg at this time

Inside this repository


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,
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):
        # 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)
        permissions = validated_data["permissions"]
        for i in permissions:
            username = i.get("username")
            perms = i.get("permissions")

            user = User.objects.get(username=username)
            for perm in get_user_perms(user, instance):
                remove_perm(perm, user, instance)

            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
    id = serializers.ReadOnlyField()
    tags = TagListSerializerField()

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