Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 76 additions & 2 deletions backend/api/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,53 @@ class Meta:
"group_name",
"type",
"mask",
"length",
)


class TemplateFieldSerializerMinified(serializers.ModelSerializer):
"""Сериализатор поля шаблона сокращенный (без полей группы)"""

type = serializers.SlugRelatedField(slug_field="type", read_only=True)
mask = serializers.CharField(source="type.mask", read_only=True)

class Meta:
model = TemplateField
fields = (
"id",
"tag",
"name",
"hint",
"type",
"mask",
"length",
)


class TemplateGroupSerializer(serializers.ModelSerializer):
"""Сериализатор группы полей шаблона"""

fields = TemplateFieldSerializerMinified(
read_only=True,
many=True,
# source="fields",
allow_empty=True,
)

class Meta:
model = TemplateField
fields = (
"id",
"name",
"fields",
)

def to_representation(self, instance):
response = super().to_representation(instance)
response["fields"].sort(key=lambda x: x["id"])
return response


class TemplateSerializerMinified(serializers.ModelSerializer):
"""Сериализатор шаблонов сокращенный."""

Expand Down Expand Up @@ -73,8 +117,8 @@ def get_is_favorited(self, template: Template) -> bool:
).exists()


class TemplateSerializer(TemplateSerializerMinified):
"""Сериализатор шаблона."""
class TemplateSerializerPlain(TemplateSerializerMinified):
"""Сериализатор шаблона (без вложенности полей в группы)."""

fields = TemplateFieldSerializer(
read_only=True,
Expand All @@ -90,6 +134,36 @@ class Meta(TemplateSerializerMinified.Meta):
read_only_fields = ("is_favorited",)


class TemplateSerializer(TemplateSerializerMinified):
"""Сериализатор шаблона (поля сгруппированы внутри grouped_fields)."""

grouped_fields = TemplateGroupSerializer(
read_only=True,
many=True,
source="field_groups",
allow_empty=True,
)
ungrouped_fields = serializers.SerializerMethodField()

class Meta(TemplateSerializerMinified.Meta):
model = Template
exclude = ("template",)
read_only_fields = (
"is_favorited",
"grouped_fields",
"ungrouped_fields",
)

def get_ungrouped_fields(self, instance):
solo_fields = instance.fields.filter(group=None).order_by("id")
return TemplateFieldSerializerMinified(solo_fields, many=True).data

def to_representation(self, instance):
response = super().to_representation(instance)
response["grouped_fields"].sort(key=lambda x: x["id"])
return response


class DocumentFieldSerializer(serializers.ModelSerializer):
"""Сериализатор поля документов."""

Expand Down
12 changes: 6 additions & 6 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"django.contrib.messages",
"django.contrib.staticfiles",
"drf_yasg",
'corsheaders',
"corsheaders",
"rest_framework",
"djoser",
"rest_framework.authtoken",
Expand All @@ -43,8 +43,8 @@
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
]

ROOT_URLCONF = "backend.urls"
Expand All @@ -67,8 +67,7 @@

WSGI_APPLICATION = "backend.wsgi.application"


if os.getenv('BD') == 'sqlite':
if os.getenv("BD") == "sqlite":
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
Expand Down Expand Up @@ -175,4 +174,5 @@
"BASE_PATH": "https://documents-template.site/api/",
}

CORS_ALLOW_ALL_ORIGINS = True # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect
CORS_ALLOW_ALL_ORIGINS = True # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect

Original file line number Diff line number Diff line change
Expand Up @@ -9,170 +9,194 @@
"name": "Наименование населенного пункта",
"hint": "г. Москва",
"group": 1,
"type": "str20"
"type": "str20",
"length": 40
},
{
"tag": "ДоговорДата",
"name": "Дата заключения договора",
"hint": "дд.мм.гггг",
"group": 1,
"type": "date"
"type": "date",
"length": 40
},
{
"tag": "НаймодательФИО",
"name": "ФИО собственника",
"hint": "Иванов Иван Иванович",
"group": 2,
"type": "fio"
"type": "fio",
"length": 40

},
{
"tag": "НаймодательПаспортНомер",
"name": "Серия и номер паспорта",
"hint": "Только цифры без пробелов",
"group": 2,
"type": "d10"
"type": "d10",
"length": 40
},
{
"tag": "НаймодательПаспортДата",
"name": "Дата выдачи паспорта",
"hint": "мм.дд.гггг",
"group": 2,
"type": "date"
"type": "date",
"length": 40
},
{
"tag": "НаймодательПаспортВыданНаименование",
"name": "Наименование выдавшего органа",
"hint": "",
"group": 2,
"type": "str40"
"type": "str40",
"length": 40
},
{
"tag": "НаймодательПаспортВыданКод",
"name": "Код подразделения",
"hint": "Только цифры, без пробелов",
"group": 2,
"type": "ddd_ddd"
"type": "ddd_ddd",
"length": 40
},
{
"tag": "НанимательФИО",
"name": "ФИО квартиросъемщика",
"hint": "Сидоров Петр Андреевич",
"group": 3,
"type": "fio"
"type": "fio",
"length": 40

},
{
"tag": "НанимательПаспортНомер",
"name": "Серия и номер паспорта",
"hint": "Только цифры без пробелов",
"group": 3,
"type": "d10"
"type": "d10",
"length": 40
},
{
"tag": "НанимательПаспортДата",
"name": "Дата выдачи паспорта",
"hint": "мм.дд.гггг",
"group": 3,
"type": "date"
"type": "date",
"length": 40
},
{
"tag": "НанимательПаспортВыданНаименование",
"name": "Наименование выдавшего органа",
"hint": "",
"group": 3,
"type": "str40"
"type": "str40",
"length": 40
},
{
"tag": "НанимательПаспортВыданКод",
"name": "Код подразделения",
"hint": "Только цифры, без пробелов",
"group": 3,
"type": "ddd_ddd"
"type": "ddd_ddd",
"length": 40
},
{
"tag": "ДоговорАдрес",
"name": "Полный адрес квартиры",
"hint": "Город, улица, дом, квартира",
"group": 4,
"type": "str40"
"type": "str40",
"length": 40
},
{
"tag": "ДоговорДокументы",
"name": "Правоустанавливающие документы (укажите наименование документа, даты, серию и номер)",
"hint": "Например, Свидетельство о государственной регистрации права от дд.мм.гггг 33 АА 99999 от 02.12.2008",
"group": 4,
"type": "str"
"type": "str",
"length": 40
},
{
"tag": "ДоговорЖильцы",
"name": "ФИО лиц, которые будут проживать в квартире",
"hint": "",
"group": 4,
"type": "list_fio"
"type": "list_fio",
"length": 40
},
{
"tag": "ПраваСрокУведомления",
"name": "Количество дней, когда необходимо предупредить владельца о расторжении договора",
"hint": "14",
"group": 5,
"type": "int"
"type": "int",
"length": 40
},
{
"tag": "ПраваСрокВъезда",
"name": "Количество дней после заключения договора, когда можно заехать в квартиру",
"hint": "14",
"group": 5,
"type": "int"
"type": "int",
"length": 40
},
{
"tag": "ПраваСрокПродления",
"name": "Количество дней до окончания договора, когда можно перезаключить его на тех же условиях",
"hint": "30",
"group": 5,
"type": "int"
"type": "int",
"length": 40
},
{
"tag": "ОплатаСпособ",
"name": "Способ оплаты",
"hint": "Например, наличными или на лицевой счет",
"group": 6,
"type": "str40"
"type": "str40",
"length": 40
},
{
"tag": "ОплатаСумма",
"name": "Сумма оплаты в месяц",
"hint": "В рублях",
"group": 6,
"type": "currency"
"type": "currency",
"length": 40
},
{
"tag": "ОплатаАванс",
"name": "Количество месяцев, за которые выплачивается аванс при въезде",
"hint": "",
"group": 6,
"type": "int"
"type": "int",
"length": 40
},
{
"tag": "ОплатаДата",
"name": "Дата оплаты по договору",
"hint": "дд.мм.гггг",
"group": 6,
"type": "date"
"type": "date",
"length": 40
},
{
"tag": "Срок",
"name": "Количество месяцев, на которые заключается договор",
"hint": "При заключении договора на более 12 мес. необходима его обязательная регистрация в Росреестре",
"group": 7,
"type": "int"
"type": "int",
"length": 40
},
{
"tag": "ДатаОкончания",
"name": "Дата окончания договора",
"hint": "дд.мм.гггг",
"group": 7,
"type": "date"
"type": "date",
"length": 40
}
],
"groups": [
Expand Down
Loading