From e88e27a56e70deae5269c75620f5d68aba1b76e1 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Thu, 7 Oct 2021 14:14:21 +0200 Subject: [PATCH] Make MailboxViewSet writable: create & update --- orchestra/contrib/mailboxes/api.py | 8 +++++++- orchestra/contrib/mailboxes/serializers.py | 24 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/orchestra/contrib/mailboxes/api.py b/orchestra/contrib/mailboxes/api.py index 16d926d3..e17b68dc 100644 --- a/orchestra/contrib/mailboxes/api.py +++ b/orchestra/contrib/mailboxes/api.py @@ -4,7 +4,7 @@ from orchestra.api import router, SetPasswordApiMixin, LogApiMixin from orchestra.contrib.accounts.api import AccountApiMixin from .models import Address, Mailbox -from .serializers import AddressSerializer, MailboxSerializer +from .serializers import AddressSerializer, MailboxSerializer, MailboxWritableSerializer class AddressViewSet(LogApiMixin, AccountApiMixin, viewsets.ModelViewSet): @@ -17,6 +17,12 @@ class MailboxViewSet(LogApiMixin, SetPasswordApiMixin, AccountApiMixin, viewsets queryset = Mailbox.objects.prefetch_related('addresses__domain').all() serializer_class = MailboxSerializer + def get_serializer_class(self): + if self.request.method == 'GET': + return self.serializer_class + + return MailboxWritableSerializer + router.register(r'mailboxes', MailboxViewSet) router.register(r'addresses', AddressViewSet) diff --git a/orchestra/contrib/mailboxes/serializers.py b/orchestra/contrib/mailboxes/serializers.py index f7be6175..ad14b11c 100644 --- a/orchestra/contrib/mailboxes/serializers.py +++ b/orchestra/contrib/mailboxes/serializers.py @@ -36,6 +36,30 @@ class MailboxSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSerializer postonly_fields = ('name', 'password') +class MailboxWritableSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSerializer): + addresses = serializers.HyperlinkedRelatedField(many=True, view_name='address-detail', queryset=Address.objects.all()) + + class Meta: + model = Mailbox + fields = ( + 'url', 'id', 'name', 'password', 'filtering', 'custom_filtering', 'addresses', 'is_active' + ) + postonly_fields = ('name', 'password') + + @transaction.atomic + def create(self, validated_data): + addresses = validated_data.pop('addresses', []) + instance = super().create(validated_data) + instance.addresses.set(addresses) + return instance + + @transaction.atomic + def update(self, instance, validated_data): + addresses = validated_data.pop('addresses', []) + instance.addresses.set(addresses) + return super().update(instance, validated_data) + + class RelatedMailboxSerializer(AccountSerializerMixin, RelatedHyperlinkedModelSerializer): class Meta: model = Mailbox