Skip to content

Instantly share code, notes, and snippets.

class SetLeaderSerializer(serializers.Serializer):
user = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all())
leader = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all())
def validate(self, data):
"""
Check that a user can't be a leader of himself.
Check that a circular relationship is not allowed.
"""
data = super().validate(data)
@extend_schema(
parameters=[OpenApiParameter("username", exclude=True)],
responses=UserListSerializer(many=True),
)
@action(detail=True, methods=("GET",))
def tree(self, request, pk):
...
...
from django.shortcuts import get_object_or_404
...
# Add this to the UserViweSet
@action(detail=True, methods=("GET",))
def tree(self, request, pk):
"""
For a given user, gets the leadership tree and returns all the users
inside that tree.
# Add this function to the UserViewSet
def create(self, request, *args, **kwargs):
"""
Creates a user in the system. The username must be unique.
The fields of password and password_confirm must match.
"""
return super().create(request, *args, **kwargs)
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin
from django_filters import rest_framework as filters
from users.serializers import UserCreateSerializer, UserDetailSerializer, UserListSerializer
from users.models import CustomUser
class UserFilter(filters.FilterSet):
username = filters.CharFilter(lookup_expr="icontains")
class UserDetailSerializer(serializers.ModelSerializer):
led_people = UserListSerializer(many=True)
class Meta:
model = CustomUser
fields = (
"id",
"username",
"first_name",
"last_name",
class UserListSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = (
"id",
"username",
)
# the serializers file
from rest_framework import serializers
from rest_framework.validators import ValidationError
from users.models import CustomUser
class UserCreateSerializer(serializers.ModelSerializer):
"""
Define again first_name and last_name to make it mandatory.
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
urlpatterns = [
#...
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
# ...
]
"SERVE_PERMISSIONS": ["rest_framework.permissions.IsAdminUser"]