class LikesSerializer(serializers.ModelSerializer): liker = UserSerializer(read_only=True) class Meta: model = Likes fields = ('liker', 'lesson') def validate(self, attrs): attrs['liker'] = self.context['user'] attrs['lesson'] = self.context['lesson'] return super().validate(attrs) def create(self, validated_data): """ If like with user and lesson already exists then delete like, else create like """ lesson = validated_data['lesson'] user = validated_data['liker'] like = Likes.objects.filter(liker=user, lesson=lesson) with transaction.atomic(): if like.exists(): like.delete() return like return Likes.objects.create(liker=user, lesson=lesson)
class CustomerSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) user_id = serializers.IntegerField(write_only=True) class Meta: model = Customer fields = ('id', 'full_name', 'cellphone', 'user_id', 'user')
class ProjectSerializer(ModelSerializer): author_info = UserSerializer(source='author', read_only=True) code_tree = SerializerMethodField('get_code_tree') def get_code_tree(self, project): return self.path_to_dict('./usr_src/{}/src/{}'.format( project.author.username, project.name)) def path_to_dict(self, path): d = { 'name': os.path.basename(path), 'last_modified': datetime.fromtimestamp(os.path.getmtime(path)) } if os.path.isdir(path): d['type'] = "directory" d['children'] = [ self.path_to_dict(os.path.join(path, x)) for x in os.listdir(path) ] else: d['type'] = "file" return d class Meta: model = Project fields = [ 'author_info', 'name', 'description', 'wrote_on', 'edited_on', 'schema', 'code_tree' ]
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "message": "User created successfully! You can now redeem your access token.", })
def find_user_by_name(request, pk): find_by_surname = False try: item = User.objects.get(name__contains=pk) except User.DoesNotExist: find_by_surname = True if (find_by_surname): try: item = User.objects.get(surname__contains=pk) except User.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = UserSerializer(item) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = UserSerializer(item, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': item.delete() return HttpResponse(status=204)
def get(self, request, pk): try: token = Token.objects.get(key=request.headers.get('Authorization')) except Exception as e: return Response({"Error": "Authorize first"}, status=status.HTTP_400_BAD_REQUEST) if token: user = User.objects.get(username=token.user.username, password=token.user.password) ser = UserSerializer(user) return Response(ser.data)
class LessonsSerializer(serializers.ModelSerializer): likes = LikesSerializer(many=True, read_only=True) owner = UserSerializer(read_only=True) lookup_field = 'slug' class Meta: model = Lessons fields = ('id', 'title', 'body', 'owner', 'slug', 'likes')
def post(self,request, *args, **kwargs): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() user = User.objects.get(email=serializer.data.get('email')) print('this is',user.id, user.email) mail_for_new_user(get_user=user) return Response(serializer.data, status=status.HTTP_201_CREATED)
def put(self, request, *args, **kwargs): serializer_data = request.data.get('user', {}) serializer = UserSerializer(request.user, data=serializer_data, partial=True) serializer.is_valid(raise_exception=True) serializer.save( ) # Обновляет данные о пользователе, если запрос типа PUT return Response(serializer.data, status=status.HTTP_200_OK)
def users_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': item = User.objects.all() serializer = UserSerializer(item, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def create(self, request, *args, **kwargs): try: auth = UserSerializer(User.objects.get(username=request.data['auth'])) role = RolesSerializer(Roles.objects.get(id=request.data['role'])) request.data['auth'] = auth.data request.data['role'] = role.data serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) except User.DoesNotExist: return Response('User does not exist!', status=status.HTTP_400_BAD_REQUEST) except Roles.DoesNotExist: return Response('Roles does not exist!', status=status.HTTP_400_BAD_REQUEST)
def user_detail(request, pk): try: item = User.objects.get(pk=pk) except User.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = UserSerializer(item) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = UserSerializer(item, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': item.delete() return HttpResponse(status=204)
def fans(self, request, pk=None): obj = self.get_object() fans = serv.get_fans(obj) serializer = UserSerializer(fans, many=True) return Response(serializer.data)
class GetSubscribersSerializer(serializers.ModelSerializer): subscriber_user = UserSerializer(source='subscriber', read_only=True) class Meta: model = Subscribers fields = ('subscriber_user', )
def get(self, request): users = User.objects.all() ser = UserSerializer(users, many=True) return Response(ser.data)
def post(self, request): user = request.data serializer = UserSerializer(data=user) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
def get(self, request, *args, **kwargs): serializer = UserSerializer()