<s> from __future__ import absolute_import , unicode_literals <EOL> from django . core . exceptions import PermissionDenied <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from rest_framework import serializers <EOL> from rest_framework . exceptions import ValidationError <EOL> from rest_framework . reverse import reverse <EOL> from acls . models import AccessControlList <EOL> from permissions import Permission <EOL> from . models import Tag <EOL> from . permissions import permission_tag_attach <EOL> class TagSerializer ( serializers . HyperlinkedModelSerializer ) : <EOL> documents = serializers . HyperlinkedIdentityField ( <EOL> view_name = '<STR_LIT>' <EOL> ) <EOL> documents_count = serializers . SerializerMethodField ( ) <EOL> class Meta : <EOL> extra_kwargs = { <EOL> '<STR_LIT:url>' : { '<STR_LIT>' : '<STR_LIT>' } , <EOL> } <EOL> fields = ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:id>' , '<STR_LIT:label>' , '<STR_LIT:url>' <EOL> ) <EOL> model = Tag <EOL> def get_documents_count ( self , instance ) : <EOL> return instance . documents . count ( ) <EOL> class NewDocumentTagSerializer ( serializers . Serializer ) : <EOL> tag = serializers . IntegerField ( <EOL> help_text = _ ( '<STR_LIT>' ) <EOL> ) <EOL> def create ( self , validated_data ) : <EOL> try : <EOL> tag = Tag . objects . get ( pk = validated_data [ '<STR_LIT>' ] ) <EOL> try : <EOL> Permission . check_permissions ( <EOL> self . context [ '<STR_LIT>' ] . user , ( permission_tag_attach , ) <EOL> ) <EOL> except PermissionDenied : <EOL> AccessControlList . objects . check_access ( <EOL> permission_tag_attach , self . context [ '<STR_LIT>' ] , tag <EOL> ) <EOL> tag . documents . add ( validated_data [ '<STR_LIT>' ] ) <EOL> except Exception as exception : <EOL> raise ValidationError ( exception ) <EOL> return { '<STR_LIT>' : tag . pk } <EOL> class DocumentTagSerializer ( TagSerializer ) : <EOL> remove = serializers . SerializerMethodField ( ) <EOL> def get_remove ( self , instance ) : <EOL> return reverse ( <EOL> '<STR_LIT>' , args = ( <EOL> self . context [ '<STR_LIT>' ] . pk , instance . pk , <EOL> ) , request = self . context [ '<STR_LIT>' ] , format = self . context [ '<STR_LIT>' ] <EOL> ) <EOL> class Meta ( TagSerializer . Meta ) : <EOL> fields = TagSerializer . Meta . fields + ( '<STR_LIT>' , ) <EOL> read_only_fields = TagSerializer . Meta . fields </s>
