From 771d2d013deb5891389a6901b3ce4635d73d1f3a Mon Sep 17 00:00:00 2001 From: Tom Hacohen Date: Wed, 26 Feb 2020 21:11:29 +0200 Subject: [PATCH] Fix creation of collection membership when creating collections. --- django_etesync/serializers.py | 16 ++++++++++++++++ django_etesync/views.py | 12 +++--------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/django_etesync/serializers.py b/django_etesync/serializers.py index 5a57900..4d4558b 100644 --- a/django_etesync/serializers.py +++ b/django_etesync/serializers.py @@ -56,6 +56,22 @@ class CollectionSerializer(serializers.ModelSerializer): def get_ctag(self, obj): return 'FIXME' + def create(self, validated_data): + """Function that's called when this serializer creates an item""" + encryption_key = validated_data.pop('encryptionKey') + instance = self.__class__.Meta.model(**validated_data) + + print(validated_data) + with transaction.atomic(): + instance.save() + models.CollectionMember(collection=instance, + user=validated_data.get('owner'), + accessLevel=models.CollectionMember.AccessLevels.ADMIN, + encryptionKey=encryption_key, + ).save() + + return instance + class CollectionItemChunkSerializer(serializers.ModelSerializer): class Meta: diff --git a/django_etesync/views.py b/django_etesync/views.py index 60e79a6..9bdb244 100644 --- a/django_etesync/views.py +++ b/django_etesync/views.py @@ -13,7 +13,7 @@ # along with this program. If not, see . from django.contrib.auth import get_user_model -from django.db import IntegrityError, transaction +from django.db import IntegrityError from django.http import Http404 from django.shortcuts import get_object_or_404 @@ -24,7 +24,7 @@ from rest_framework.decorators import action as action_decorator from rest_framework.response import Response from . import app_settings, paginators -from .models import Collection, CollectionItem, CollectionMember +from .models import Collection, CollectionItem from .serializers import ( CollectionSerializer, CollectionItemSerializer, @@ -72,13 +72,7 @@ class CollectionViewSet(BaseViewSet): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): try: - with transaction.atomic(): - col = serializer.save(owner=self.request.user) - CollectionMember(collection=col, - user=self.request.user, - accessLevel=CollectionMember.AccessLevels.ADMIN, - encryptionKey=serializer.validated_data['encryptionKey'] - ).save() + serializer.save(owner=self.request.user) except IntegrityError: content = {'code': 'integrity_error'} return Response(content, status=status.HTTP_400_BAD_REQUEST)