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."),