From 5d9b47531ba99a0ee1803d6818814c9a3d1206b8 Mon Sep 17 00:00:00 2001 From: Tom Hacohen Date: Tue, 22 Sep 2020 12:17:33 +0300 Subject: [PATCH] Collectin: make sure collections always have a unique UID. --- django_etebase/models.py | 13 +++++++++++++ django_etebase/serializers.py | 2 ++ 2 files changed, 15 insertions(+) diff --git a/django_etebase/models.py b/django_etebase/models.py index d3405f1..914b763 100644 --- a/django_etebase/models.py +++ b/django_etebase/models.py @@ -21,7 +21,10 @@ from django.db.models import Q from django.utils.functional import cached_property from django.utils.crypto import get_random_string +from rest_framework import status + from . import app_settings +from .exceptions import EtebaseValidationError UidValidator = RegexValidator(regex=r'^[a-zA-Z0-9\-_]{20,}$', message='Not a valid UID') @@ -57,6 +60,16 @@ class Collection(models.Model): return stoken.uid + def validate_unique(self, exclude=None): + super().validate_unique(exclude=exclude) + if exclude is None or 'main_item' in exclude: + return + + if self.__class__.objects.filter(owner=self.owner, main_item__uid=self.main_item.uid) \ + .exclude(id=self.id).exists(): + raise EtebaseValidationError('unique_uid', 'Collection with this uid already exists', + status_code=status.HTTP_409_CONFLICT) + class CollectionItem(models.Model): uid = models.CharField(db_index=True, blank=False, diff --git a/django_etebase/serializers.py b/django_etebase/serializers.py index 3c32e10..d371f13 100644 --- a/django_etebase/serializers.py +++ b/django_etebase/serializers.py @@ -297,6 +297,8 @@ class CollectionSerializer(BetterErrorsMixin, serializers.ModelSerializer): main_item = models.CollectionItem.objects.create(**main_item_data, collection=instance) instance.main_item = main_item + + instance.full_clean() instance.save() process_revisions_for_item(main_item, revision_data)