From 867d9afe651cf977270f63f5180e5d92310701a8 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Fri, 18 Jun 2021 11:11:50 +0200 Subject: [PATCH] Make /aoi/addresses/ endpoint writable --- orchestra/contrib/mailboxes/serializers.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/orchestra/contrib/mailboxes/serializers.py b/orchestra/contrib/mailboxes/serializers.py index c0ab4639..f7be6175 100644 --- a/orchestra/contrib/mailboxes/serializers.py +++ b/orchestra/contrib/mailboxes/serializers.py @@ -1,3 +1,4 @@ +from django.db import transaction from rest_framework import serializers from orchestra.api.serializers import SetPasswordHyperlinkedSerializer, RelatedHyperlinkedModelSerializer @@ -43,7 +44,7 @@ class RelatedMailboxSerializer(AccountSerializerMixin, RelatedHyperlinkedModelSe class AddressSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer): domain = RelatedDomainSerializer() - mailboxes = RelatedMailboxSerializer(many=True, required=False) #allow_add_remove=True + mailboxes = RelatedMailboxSerializer(many=True, required=False) class Meta: model = Address @@ -51,16 +52,21 @@ class AddressSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSeri def validate(self, attrs): attrs = super(AddressSerializer, self).validate(attrs) - if not attrs['mailboxes'] and not attrs['forward']: + mailboxes = attrs.get('mailboxes', []) + forward = attrs.get('forward', '') + if not mailboxes and not forward: raise serializers.ValidationError("A mailbox or forward address should be provided.") return attrs + @transaction.atomic def create(self, validated_data): - mailboxes = validated_data.pop('mailboxes') - - # assign address to same account than domain - account = validated_data['domain'].account - obj = self.Meta.model.objects.create(account=account, **validated_data) - + mailboxes = validated_data.pop('mailboxes', []) + obj = super().create(validated_data) obj.mailboxes.set(mailboxes) return obj + + @transaction.atomic + def update(self, instance, validated_data): + mailboxes = validated_data.pop('mailboxes', []) + instance.mailboxes.set(mailboxes) + return super().update(instance, validated_data)