From 49673d64afe230e7582a9eac8bb042a4668333d1 Mon Sep 17 00:00:00 2001 From: dormantman Date: Tue, 14 Jan 2020 18:20:57 +0300 Subject: [PATCH] Added automatic username creation --- apps/authorization/serializers/common.py | 18 +++++++++++++----- apps/utils/methods.py | 10 +++++++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/apps/authorization/serializers/common.py b/apps/authorization/serializers/common.py index e6a9bdc7..4ebc1c99 100644 --- a/apps/authorization/serializers/common.py +++ b/apps/authorization/serializers/common.py @@ -18,6 +18,7 @@ from utils.tokens import GMRefreshToken # Serializers class SignupSerializer(serializers.ModelSerializer): """Signup serializer serializer mixin""" + class Meta: model = account_models.User fields = ( @@ -35,11 +36,18 @@ class SignupSerializer(serializers.ModelSerializer): def validate_username(self, value): """Custom username validation""" - valid = utils_methods.username_validator(username=value) - if not valid: - raise utils_exceptions.NotValidUsernameError() - if account_models.User.objects.filter(username__iexact=value).exists(): - raise serializers.ValidationError() + if value: + valid = utils_methods.username_validator(username=value) + if not valid: + raise utils_exceptions.NotValidUsernameError() + if account_models.User.objects.filter(username__iexact=value).exists(): + raise serializers.ValidationError() + + else: + value = utils_methods.username_random() + while account_models.User.objects.filter(username__iexact=value).exists(): + value = utils_methods.username_random() + return value def validate_email(self, value): diff --git a/apps/utils/methods.py b/apps/utils/methods.py index 18575c07..71101a9e 100644 --- a/apps/utils/methods.py +++ b/apps/utils/methods.py @@ -55,6 +55,14 @@ def username_validator(username: str) -> bool: return True +def username_random(): + """Generate random username""" + return '{letters}{digits}'.format( + letters=''.join([random.choice(string.ascii_lowercase) for _ in range(5)]), + digits=random.randrange(100, 1000) + ) + + def image_path(instance, filename): """Determine avatar path method.""" filename = '%s.jpeg' % generate_code() @@ -184,4 +192,4 @@ def get_image_meta_by_url(url) -> (int, int, int): image_raw = requests.get(url) image = Image.open(BytesIO(image_raw.content)) width, height = image.size - return int(image_raw.headers.get('content-length')), width, height \ No newline at end of file + return int(image_raw.headers.get('content-length')), width, height