From 91b39b877bcfb6c207477fb148092bf8088a1b3a Mon Sep 17 00:00:00 2001 From: Yuri Pomazkin <1yunker@gmail.com> Date: Tue, 28 Nov 2023 14:34:47 +0500 Subject: [PATCH] Added address_line validation and strip multiple spaces --- backend/api/serializers.py | 4 ++++ backend/projects/models.py | 4 +++- backend/projects/validators.py | 26 ++++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/backend/api/serializers.py b/backend/api/serializers.py index 545a721..01a14f5 100644 --- a/backend/api/serializers.py +++ b/backend/api/serializers.py @@ -1,3 +1,5 @@ +import re + from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction @@ -430,6 +432,7 @@ def create(self, validated_data): address, _ = Address.objects.get_or_create( **validated_data.pop('event_address') ) + address.address_line = re.sub(' +', ' ', address.address_line) project_instanse = Project.objects.create( event_address=address, **validated_data ) @@ -443,6 +446,7 @@ def update(self, instance, validated_data): address = instance.event_address for attr, value in address_data.items(): setattr(address, attr, value) + address.address_line = re.sub(' +', ' ', address.address_line) address.save() return super(ProjectSerializer, self).update(instance, validated_data) diff --git a/backend/projects/models.py b/backend/projects/models.py index 07c3a38..3375ac1 100644 --- a/backend/projects/models.py +++ b/backend/projects/models.py @@ -11,6 +11,7 @@ from .validators import ( LengthValidator, regex_string_validator, + validate_address, validate_name, validate_ogrn, validate_phone_number, @@ -212,7 +213,8 @@ class Address(models.Model): """ address_line = models.CharField( - max_length=100, verbose_name='Адрес в одну строчку' + max_length=100, verbose_name='Адрес в одну строчку', + validators=[validate_address] ) street = models.CharField(max_length=75, verbose_name='Улица') house = models.CharField(max_length=5, verbose_name='Дом') diff --git a/backend/projects/validators.py b/backend/projects/validators.py index 74bcc5d..e35fbbb 100644 --- a/backend/projects/validators.py +++ b/backend/projects/validators.py @@ -223,3 +223,29 @@ def validate_text_field(value): min_length_validator(value) max_length_validator(value) regex_validator(value) + + +def validate_address(value): + """ + Валидация адреса. + """ + MIN_LEN = 2 + MAX_LEN = 100 + NAME_REGEX = r'^[A-Za-zА-Яа-я0-9 ,-.]+$' + + min_length_validator = MinLengthValidator( + MIN_LEN, + message=f'Минимальная длина поля должна быть: {MIN_LEN}.', + ) + max_length_validator = MaxLengthValidator( + MAX_LEN, + message=f'Максимальная длина поля должна быть: {MAX_LEN}.', + ) + regex_validator = RegexValidator( + regex=NAME_REGEX, + message='Недопустимые символы в адресе. Разрешены латинские ' + 'и кириллические буквы, цифры, пробел, запятая, точка и тире.', + ) + min_length_validator(value) + max_length_validator(value) + regex_validator(value)