From 757dfdd91492b9f7878b8d1eb4aff429ca94d17e Mon Sep 17 00:00:00 2001 From: Pierre-antoine Comby Date: Thu, 26 Mar 2020 17:45:24 +0100 Subject: [PATCH] serializer config --- apps/note/api/serializers.py | 6 +++++- apps/note/api/views.py | 9 ++++++++- apps/note/models/notes.py | 6 +++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/note/api/serializers.py b/apps/note/api/serializers.py index a51b4263..05c35aa5 100644 --- a/apps/note/api/serializers.py +++ b/apps/note/api/serializers.py @@ -78,7 +78,11 @@ class AliasSerializer(serializers.ModelSerializer): class Meta: model = Alias fields = '__all__' - read_only_fields = ('note', ) + + def validate(self, attrs): + instance = Alias(**attrs) + instance.clean() + return attrs class NotePolymorphicSerializer(PolymorphicSerializer): diff --git a/apps/note/api/views.py b/apps/note/api/views.py index fc4a0e8f..3a29b522 100644 --- a/apps/note/api/views.py +++ b/apps/note/api/views.py @@ -41,7 +41,7 @@ class NotePolymorphicViewSet(ReadOnlyProtectedModelViewSet): return queryset.distinct() -class AliasViewSet(ReadProtectedModelViewSet): +class AliasViewSet(viewsets.ModelViewSet): """ REST API View set. The djangorestframework plugin will get all `Alias` objects, serialize it to JSON with the given serializer, @@ -53,6 +53,13 @@ class AliasViewSet(ReadProtectedModelViewSet): search_fields = ['$normalized_name', '$name', '$note__polymorphic_ctype__model', ] ordering_fields = ['name', 'normalized_name'] + def get_serializer_class(self): + serializer_class = self.serializer_class + if self.request.method in ['PUT', 'PATCH']: + #alias owner cannot be change once establish + setattr(serializer_class.Meta, 'read_only_fields', ('note',)) + return serializer_class + def get_queryset(self): """ Parse query and apply filters. diff --git a/apps/note/models/notes.py b/apps/note/models/notes.py index b6b00aa8..2fa63906 100644 --- a/apps/note/models/notes.py +++ b/apps/note/models/notes.py @@ -228,7 +228,7 @@ class Alias(models.Model): for cat in {'M', 'P', 'Z', 'C'})).casefold() def clean(self): - normalized_name = Alias.normalize(self.name) + normalized_name = self.normalize(self.name) if len(normalized_name) >= 255: raise ValidationError(_('Alias is too long.'), code='alias_too_long') @@ -242,6 +242,10 @@ class Alias(models.Model): pass self.normalized_name = normalized_name + def save(self,*args,**kwargs): + self.normalized_name = self.normalize(self.name) + super().save(*args,**kwargs) + def delete(self, using=None, keep_parents=False): if self.name == str(self.note): raise ValidationError(_("You can't delete your main alias."),