Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[~] Исправлены сигналы на создание пользователя, разделены на отдельн… #154

Merged
merged 2 commits into from
Apr 3, 2024
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
2 changes: 1 addition & 1 deletion src/backend/api/v1/profile/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True

return obj.owner or obj.creator == request.user
return obj.user == request.user
52 changes: 33 additions & 19 deletions src/backend/api/v1/profile/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,31 @@
from apps.projects.models import Skill, Specialist


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

class Meta:
model = Profile
fields = "__all__"
# fields = "__all__"
exclude = ["visible_status_contacts", "visible_status", "user"]

def to_representation(self, instance):
user = self.context["request"].user
visible_status_contacts = instance.visible_status_contacts
is_organizer = user.is_authenticated and user.is_organizer
base_queryset = super().to_representation(instance)
if visible_status_contacts in [Profile.NOBODY] or (
not user.is_organizer
not is_organizer
and visible_status_contacts in [Profile.CREATOR_ONLY]
):
self.fields.pop("phone_number")
self.fields.pop("email")
self.fields.pop("telegram")

return super().to_representation(instance)


class ProfileUpdateSerializer(serializers.ModelSerializer):
"""Сериализатор на редактирование профиля пользователя."""

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

class Meta:
model = Profile
fields = "__all__"
base_queryset.pop("phone_number")
base_queryset.pop("email")
base_queryset.pop("telegram_nick")
return base_queryset


class UserSkillSerializer(serializers.ModelSerializer):
skills = serializers.PrimaryKeyRelatedField(
skill = serializers.PrimaryKeyRelatedField(
queryset=Skill.objects.all(), many=True
)

Expand Down Expand Up @@ -67,3 +59,25 @@ class Meta:
message="Этот специализация вами уже была выбрана",
)
]


class ProfileUpdateSerializer(serializers.ModelSerializer):
"""Сериализатор на редактирование профиля пользователя."""

user = serializers.HiddenField(default=serializers.CurrentUserDefault())
userskills = UserSkillSerializer(many=True, read_only=True)
userspecialization = UserSpecializationSerializer(
many=True, read_only=True
)

class Meta:
model = Profile
exclude = ["visible_status_contacts", "visible_status"]


class ProfileVisibilitySerializer(serializers.ModelSerializer):
"""Сериализатор на управление видимостью профиля"""

class Meta:
model = Profile
fields = ["visible_status_contacts", "visible_status"]
9 changes: 7 additions & 2 deletions src/backend/api/v1/profile/signals.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

from apps.profile.models import Profile
from apps.users.models import User


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
"""Функция автоматического создания профиля при создании пользователя"""
if created:
Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile, _ = Profile.objects.get_or_create(user=instance)
instance.profile.save()
16 changes: 12 additions & 4 deletions src/backend/api/v1/profile/urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
from django.urls import path
from django.urls import include, path
from rest_framework.routers import DefaultRouter

from api.v1.profile.views import ProfileListAPIView, ProfileView
from api.v1.profile.views import (
ProfileUpdateView,
ProfileViewSet,
ProfileVisibilityView,
)

router = DefaultRouter()
router.register(r"profiles", ProfileViewSet)
urlpatterns = [
path("profiles/", ProfileListAPIView.as_view(), name="profile-list"),
path("profiles/<pk>", ProfileView.as_view(), name="profile"),
path("", include(router.urls)),
path("profile_update/<pk>/", ProfileUpdateView.as_view()),
path("profile_visibility/<pk>/", ProfileVisibilityView.as_view()),
]
30 changes: 23 additions & 7 deletions src/backend/api/v1/profile/views.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
from rest_framework import generics
from rest_framework import generics, viewsets

from api.v1.profile.permissions import IsOwnerOrReadOnly
from api.v1.profile.serializers import (
ProfileSerializer,
ProfileUpdateSerializer,
ProfileVisibilitySerializer,
)
from apps.profile.models import Profile


class ProfileView(generics.UpdateAPIView):
"""Представление на изменение данных в профиле"""
class ProfileUpdateView(generics.RetrieveUpdateAPIView):
"""Представление на редактирование профиля"""

queryset = Profile.objects.all()
queryset = Profile.objects.prefetch_related("userskills").prefetch_related(
"userspecialization"
)
serializer_class = ProfileUpdateSerializer
permission_classes = [IsOwnerOrReadOnly]
permission_classes = [
IsOwnerOrReadOnly,
]


class ProfileListAPIView(generics.ListAPIView):
"""Список профилей в зависимости от их видимости"""
class ProfileViewSet(viewsets.ReadOnlyModelViewSet):
"""Представление на просмотр профиля в зависимости от настроек видимости"""

queryset = Profile.objects.all()
serializer_class = ProfileSerializer

def get_queryset(self):
Expand All @@ -33,3 +39,13 @@ def get_queryset(self):
queryset = queryset.filter(visible_status=Profile.ALL)

return queryset


class ProfileVisibilityView(generics.RetrieveUpdateAPIView):
"""Представление на редактирование видимости профиля"""

queryset = Profile.objects.all()
serializer_class = ProfileVisibilitySerializer
permission_classes = [
IsOwnerOrReadOnly,
]
35 changes: 28 additions & 7 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-24 16:00
# Generated by Django 5.0.1 on 2024-04-02 04:26

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

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

Expand Down Expand Up @@ -94,6 +94,7 @@ class Migration(migrations.Migration):
(
"about",
models.TextField(
blank=True,
max_length=750,
validators=[
django.core.validators.RegexValidator(
Expand All @@ -110,8 +111,8 @@ class Migration(migrations.Migration):
(
"portfolio_link",
models.URLField(
blank=True,
max_length=256,
unique=True,
validators=[
django.core.validators.URLValidator(
message="Введите корректный URL"
Expand All @@ -125,6 +126,7 @@ class Migration(migrations.Migration):
(
"birthday",
models.DateField(
null=True,
validators=[apps.profile.validators.BirthdayValidator],
verbose_name="Дата рождения",
),
Expand All @@ -147,26 +149,27 @@ class Migration(migrations.Migration):
(4, "senior"),
(5, "lead"),
],
null=True,
verbose_name="Уровень квалификации",
),
),
(
"ready_to_participate",
models.BooleanField(
choices=[(True, "Готов"), (False, "Не готов")],
default=False,
null=True,
verbose_name="Готовность к участию в проектах",
),
),
(
"visibile_status",
"visible_status",
models.PositiveSmallIntegerField(
choices=[
(1, "All"),
(2, "Only creator"),
(3, "Nobody"),
],
default="All",
default=1,
verbose_name="Видимость",
),
),
Expand All @@ -178,7 +181,7 @@ class Migration(migrations.Migration):
(2, "Only creator"),
(3, "Nobody"),
],
default=3,
default=1,
verbose_name="Видимость контактов",
),
),
Expand Down Expand Up @@ -207,6 +210,14 @@ class Migration(migrations.Migration):
verbose_name="ID",
),
),
(
"profile",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="profile.profile",
),
),
(
"skill",
models.ForeignKey(
Expand All @@ -224,6 +235,7 @@ class Migration(migrations.Migration):
],
options={
"verbose_name": "Навык пользователя",
"default_related_name": "userskills",
},
),
migrations.CreateModel(
Expand All @@ -238,6 +250,14 @@ class Migration(migrations.Migration):
verbose_name="ID",
),
),
(
"profile",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="profile.profile",
),
),
(
"specialization",
models.ForeignKey(
Expand All @@ -255,6 +275,7 @@ class Migration(migrations.Migration):
],
options={
"verbose_name": "Специализация пользователя",
"default_related_name": "userspecialization",
},
),
migrations.AddConstraint(
Expand Down
Loading