Skip to content

Commit

Permalink
[~] Отредактирована видимость контактов и всего профиля
Browse files Browse the repository at this point in the history
  • Loading branch information
Nadya2502 committed Mar 19, 2024
1 parent e70b7b7 commit d539bd9
Show file tree
Hide file tree
Showing 6 changed files with 147 additions and 134 deletions.
46 changes: 28 additions & 18 deletions src/backend/api/v1/profile/serializers.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,46 @@
from rest_framework import generics, serializers

from apps.profile.models import Profile, UserSkill
from apps.projects.models import Project


class ProfileUpdateSerializer(serializers.ModelSerializer):
"""Модель сериализатора профиля с учетом выбора видимости контактов"""

user = serializers.HiddenField(default=serializers.CurrentUserDefault())

class Meta:
model = Profile
fields = "__all__"
fields = [
"avatar",
"name",
"about",
"portfolio_link",
"birthday",
"country",
"city",
"specialization",
"skill",
"level",
"ready_to_participate",
]

def to_representation(self, instance):
user = self.context["request"].user
visibile_status = instance.visible_choices

representation = {}
visible_status_contacts = instance.visible_status_contacts

if user.is_authenticated:
if visibile_status == "all":
representation["email"] = instance.email
representation["telegram"] = instance.telegram
representation["phone_number"] = instance.phone_number
elif visibile_status == "only_creator" and instance.user == user:
representation["email"] = instance.email
representation["telegram"] = instance.telegram
representation["phone_number"] = instance.phone_number
else:
representation["message"] = "Недоступно"
else:
representation["message"] = "Недоступно"

return representation
if (
visible_status_contacts == 2
and Project.objects.filter(creator=user).exists()
):
return super().to_representation(instance)
if visible_status_contacts == 3:
self.fields.pop("phone_number")
self.fields.pop("email")
self.fields.pop("telegram")
return super().to_representation(instance)
return {}


class UserSkillSerializer(serializers.ModelSerializer):
Expand Down
33 changes: 20 additions & 13 deletions src/backend/api/v1/profile/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from rest_framework import generics, status
from rest_framework.response import Response
from django.db.models import Q
from rest_framework import generics

from api.v1.profile.permissions import IsOwnerOrReadOnly
from api.v1.profile.serializers import ProfileUpdateSerializer
from apps.profile.models import Profile
from apps.projects.models import Project


class ProfileView(generics.RetrieveAPIView):
Expand All @@ -21,17 +22,23 @@ class ProfileListAPIView(generics.ListAPIView):

def get_queryset(self):
user = self.request.user
visibile_status = self.request.query_params.get(
"visibile_status", "all"
visible_status = self.request.query_params.get("visible_status", "All")
is_organizer = (
user.is_authenticated
and Project.objects.filter(creator=user).exists()
)
if visibile_status == "all":
queryset = Profile.objects.all()
elif visibile_status == "creator":
queryset = Profile.objects.filter(
visibility="creator"
) # Выводится в списке, если стоит видимость всем или организаторам проекта

if visible_status == "Only creator" and user.is_authenticated:
# Проверяем, является ли пользователь организатором каких-либо проектов
if is_organizer:
queryset = Profile.objects.filter(
visible_status__in=["All", "Only creator"]
)
else:
queryset = Profile.objects.filter(
visible_status="all"
) # Если пользователь не организатор, возвращаем только то, что видно всем
else:
queryset = (
Profile.objects.none()
) # Пустой queryset, если не выбраны организаторы
queryset = Profile.objects.filter(visible_status="All")

return queryset
6 changes: 1 addition & 5 deletions src/backend/apps/profile/constants.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
BOOL_CHOICES = [(True, "Готов"), (False, "Не готов")]
MAX_LENGTH_NAME = 30
MAX_LENGTH_EMAIL = 256
MAX_LENGTH_TELEGRAM = 32
MAX_LENGTH_PHONE_NUMBER = 12
MAX_LENGTH_COUNTRY = 255
MAX_LENGTH_CITY = 255
MAX_LENGTH_ABOUT = 750
MAX_LENGTH_URL = 256
MIN_LENGTH_NAME = 2
MIN_LENGTH_ABOUT = 50
MIN_LENGTH_PORTFOLIO = 5
MIN_LENGTH_TELEGRAM = 5
MIN_LENGTH_EMAIL = 5
VISIBLE_CHOICES = [
(1, "All"),
(2, "Only creator"),
(3, "Nobody"),
]
LEVEL_CHOICES = [(1, "Junior"), (2, "Middle"), (3, "Senior"), (4, "Lead")]
115 changes: 62 additions & 53 deletions src/backend/apps/profile/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.0.1 on 2024-03-14 06:48
# Generated by Django 5.0.1 on 2024-03-19 12:08

import apps.profile.validators
import django.core.validators
Expand All @@ -11,7 +11,7 @@ class Migration(migrations.Migration):
initial = True

dependencies = [
("general", "0002_section_page_id"),
("general", "0002_alter_specialist_specialization_and_more"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

Expand Down Expand Up @@ -60,7 +60,7 @@ class Migration(migrations.Migration):
"specialization",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="general.specialization",
to="general.specialist",
),
),
(
Expand All @@ -84,6 +84,44 @@ class Migration(migrations.Migration):
verbose_name="ID",
),
),
(
"phone_number",
models.TextField(
blank=True,
max_length=12,
validators=[
django.core.validators.RegexValidator(
message="Телефон может содержать: цифры, спецсимволы, длина не должна превышать 12 символов",
regex="^\\+7\\(\\d{3}\\)\\d{3}-\\d{2}-\\d{2}$",
)
],
verbose_name="Номер телефона",
),
),
(
"telegram_nick",
models.CharField(
blank=True,
max_length=32,
validators=[
django.core.validators.MinLengthValidator(
limit_value=5,
message="Длина поля от 5 до 32 символов.",
),
django.core.validators.RegexValidator(
message="Введите корректное имя пользователя. Оно может состоять из латинских букв, цифр и символа подчеркивания.",
regex="^[a-zA-Z0-9_]+$",
),
],
verbose_name="Ник в телеграм",
),
),
(
"email",
models.EmailField(
blank=True, max_length=256, verbose_name="E-mail"
),
),
(
"avatar",
models.ImageField(
Expand Down Expand Up @@ -140,50 +178,6 @@ class Migration(migrations.Migration):
],
),
),
(
"phone_number",
models.TextField(
max_length=12,
validators=[
django.core.validators.RegexValidator(
message="Телефон может содержать: цифры, спецсимволы, длина не должна превышать 12 символов",
regex="^\\+7\\(\\d{3}\\)\\d{3}-\\d{2}-\\d{2}$",
)
],
verbose_name="Номер телефона",
),
),
(
"telegram",
models.CharField(
max_length=32,
validators=[
django.core.validators.RegexValidator(
message="Некорректный формат введенных данных",
regex="^[a-zA-Z0-9_]+$",
),
django.core.validators.MinLengthValidator(
limit_value=5
),
],
verbose_name="Ник в телеграме",
),
),
(
"email",
models.EmailField(
max_length=256,
validators=[
django.core.validators.MinLengthValidator(
limit_value=5
),
django.core.validators.EmailValidator(
message="Введите корректный e-mail"
),
],
verbose_name="E-mail",
),
),
(
"birthday",
models.DateField(
Expand All @@ -203,11 +197,10 @@ class Migration(migrations.Migration):
"level",
models.IntegerField(
choices=[
(1, "intern"),
(2, "junior"),
(3, "middle"),
(4, "senior"),
(5, "lead"),
(1, "Junior"),
(2, "Middle"),
(3, "Senior"),
(4, "Lead"),
],
verbose_name="Уровень квалификации",
),
Expand All @@ -216,6 +209,7 @@ class Migration(migrations.Migration):
"ready_to_participate",
models.BooleanField(
choices=[(True, "Готов"), (False, "Не готов")],
default=False,
verbose_name="Готовность к участию в проектах",
),
),
Expand All @@ -227,10 +221,22 @@ class Migration(migrations.Migration):
(2, "Only creator"),
(3, "Nobody"),
],
default=1,
default="All",
verbose_name="Видимость",
),
),
(
"visible_status_contacts",
models.PositiveSmallIntegerField(
choices=[
(1, "All"),
(2, "Only creator"),
(3, "Nobody"),
],
default=3,
verbose_name="Видимость контактов",
),
),
(
"user",
models.OneToOneField(
Expand All @@ -256,5 +262,8 @@ class Migration(migrations.Migration):
),
),
],
options={
"abstract": False,
},
),
]
Loading

0 comments on commit d539bd9

Please sign in to comment.