def edit_user(request, pk=None): if request.content_type == 'application/json': user = Users.objects.filter(id=pk).first() if user: if request.method == 'PUT': if len(request.data) != 0: try: if request.data['password']: request.data['password'] = make_password( request.data['password']) except: pass user_serializer = UserSerializer(user, data=request.data) if user_serializer.is_valid(): user_serializer.save() response = user_serializer.data response.pop('password', None) response.pop('is_active', None) response.pop('last_login', None) response.pop('is_admin', None) return Response(response, status=status.HTTP_200_OK) return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response({'message': 'empty body'}, status=status.HTTP_400_BAD_REQUEST) return Response({'message': 'User not found'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( { "error": "Request should have 'Content-Type' header with value 'application/json'" }, status=status.HTTP_403_FORBIDDEN)
def put(self, request: Request, pk: int) -> Response: user = self.get_object(pk) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def api_users_create(request): if request.content_type == 'application/json': # create user if request.method == 'POST': if len(request.data) != 0: request.data['password'] = make_password( request.data['password']) user_serializer = UserSerializer(data=request.data) if user_serializer.is_valid(): user_serializer.save() response = user_serializer.data response.pop('password', None) response.pop('is_active', None) response.pop('last_login', None) response.pop('is_admin', None) return Response(response, status=status.HTTP_201_CREATED) return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response({'message': 'empty body'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( { "error": "Request should have 'Content-Type' header with value 'application/json'" }, status=status.HTTP_403_FORBIDDEN)
def post(self, request: Request) -> Response: serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() response = { "user": serializer.data, } return Response(response, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class OwnershipTransferSerializer(serializers.ModelSerializer): """Serializer for ownership transfers""" order = PurchaseOrderSerializer() previous_owner = UserSerializer() current_owner = UserSerializer() created_by = UserSerializer() modified_by = UserSerializer() items = InventoryItemSerializer(many=True) class Meta: model = OwnershipTransfer fields = ('id', 'order', 'previous_owner', 'current_owner', 'items', 'date_transferred', 'date_created', 'date_modified', 'created_by', 'modified_by')
def user_api_view(request): #list if request.method == 'GET': users = User.objects.all().values('id','username','email','password') users_serializer = UserListSerializer(users,many=True) #se convietes a json a partir de la sonsulta (users) return Response(users_serializer.data,status=status.HTTP_200_OK) #create elif request.method == 'POST': user_serializer = UserSerializer(data = request.data) if user_serializer.is_valid(): user_serializer.save() return Response({'message':'user create'},status=status.HTTP_201_CREATED) return Response(user_serializer.errors,status=status.HTTP_400_BAD_REQUEST)
def delete_user(request, pk=None): if request.content_type == 'application/json': user = Users.objects.filter(id=pk).first() if user: # delete user if request.method == 'DELETE': user = Users.objects.filter(id=pk).first() user_serializer = UserSerializer(user) response = user_serializer.data response.pop('password', None) response.pop('is_active', None) response.pop('last_login', None) response.pop('is_admin', None) user.delete() return Response(response, status=status.HTTP_200_OK) return Response({'message': 'User not found'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( { "error": "Request should have 'Content-Type' header with value 'application/json'" }, status=status.HTTP_403_FORBIDDEN)
def edit_p_user(request, pk=None): if request.content_type == 'application/json': user = Users.objects.filter(id=pk).first() if user: if request.method == 'PATCH': if len(request.data) != 0: list_field_edit = user.edit_user_patch(request) Users.objects.filter(id=pk).update(**list_field_edit) user_update = Users.objects.filter(id=pk).first() user_serializer = UserSerializer(user_update) response = user_serializer.data response.pop('password', None) response.pop('is_active', None) response.pop('last_login', None) response.pop('is_admin', None) return Response(response, status=status.HTTP_200_OK) else: return Response({'message': 'empty body'}, status=status.HTTP_400_BAD_REQUEST) return Response({'message': 'User not found'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( { "error": "Request should have 'Content-Type' header with value 'application/json'" }, status=status.HTTP_403_FORBIDDEN)
def my_jwt_response_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={ 'request': request }).data }
def login(request): if request.method == 'POST': if request.content_type == 'application/json': # list users if request.method == 'POST': if len(request.data) != 0: email = request.data['email'] password = request.data['password'] user = authenticate(email=email, password=password) if user is not None: refresh = RefreshToken.for_user(user) print(refresh) user.token = refresh.access_token user.save() user_serializer = UserSerializer(user) response = user_serializer.data response.pop('password', None) return Response(response, status=status.HTTP_200_OK) else: return Response({"error": "Error in user or password"}, status=status.HTTP_401_UNAUTHORIZED) else: return Response({'message': 'empty body'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( { "error": "Request should have 'Content-Type' header with value 'application/json'" }, status=status.HTTP_403_FORBIDDEN)
def user_api_view(request): # permission_classes = (IsAuthenticated,) # list if request.user.is_authenticated: if request.method == 'GET': # queryset users = User.objects.all().values('id', 'username', 'email', 'password', 'name') users_serializer = UserListSerializer(users, many=True) # test_data = { # 'name':'developer', # 'email':'*****@*****.**' # } # test_users = TestUserSerializer(data = test_data, context = test_data) # if test_users.is_valid(): # user_instance =test_users.save() # print(user_instance) # # print("paso validaciones") # else: # print(test_users.errors) return Response(users_serializer.data, status=status.HTTP_200_OK) # create elif request.method == 'POST': users_serializer = UserSerializer(data=request.data) # validation if users_serializer.is_valid(): users_serializer.save() # return Response({'message': 'Usuario Eliminado correctamente!!'}, status=status.HTTP_201_CREATED) return Response(users_serializer.data, status=status.HTTP_201_CREATED) return Response(users_serializer.errors) else: return Response({'message': 'Inicie Sesion!!'}, status=status.HTTP_400_BAD_REQUEST)
def user_api_view(request): # List if request.method == 'GET': # Consulta users = User.objects.all().values('id', 'username', 'email', 'password') users_serializer = UserListSerializer(users, many=True) return Response(users_serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': user_serializer = UserSerializer(data=request.data) if user_serializer.is_valid(): user_serializer.save() return Response({'message': 'Usuario creado correctamente!'}, status=status.HTTP_201_CREATED) return Response(user_serializer.errors)
class WorkInProgressSerializer(serializers.ModelSerializer): """Serializer for wip's""" product = ProductDesignSerializer() workshop = WorkshopSerializer() received_from = UserSerializer() delivered_to = UserSerializer() created_by = UserSerializer() modified_by = UserSerializer() class Meta: model = WorkInProgress fields = ('id', 'product', 'workshop', 'process', 'received_items', 'quantity_received', 'date_received', 'received_from', 'delivered_items', 'quantity_delivered', 'date_delivered', 'delivered_to', 'date_created', 'date_modified', 'created_by', 'modified_by')
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] })
def user_detail_api_view(request, pk=None): # Consulta user = User.objects.filter(id=pk).first() # Validacion if user: # Retrieve if request.method == 'GET': user_serializer = UserSerializer(user) return Response(user_serializer.data, status=status.HTTP_200_OK) # Update elif request.method == 'PUT': user_serializer = UserSerializer(user, data=request.data) if user_serializer.is_valid(): user_serializer.save() return Response(user_serializer.data, status=status.HTTP_200_OK) return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Delete elif request.method == 'DELETE': user.delete() return Response({'message': 'Usuario eliminado correctamente!'}, status=status.HTTP_200_OK) return Response({'message': 'Usuario no encontrado!'}, status=status.HTTP_400_BAD_REQUEST)
def user_detail_api_view(request,pk): #queryset user = User.objects.filter(id=pk).first() #validation if user: #retrieve if request.method == 'GET': user_serializer = UserSerializer(user) return Response(user_serializer.data,status=status.HTTP_201_CREATED) #update elif request.method == 'PUT': user_serializer = UserSerializer(user,data = request.data) # en envia la instancia del objeto y el dato que se quiere actualizar if user_serializer.is_valid(): user_serializer.save() return Response(user_serializer.data,status=status.HTTP_201_CREATED) return Response(user_serializer.errors,status=status.HTTP_400_BAD_REQUEST) #delete elif request.method == 'DELETE': user.delete() return response({'message':'User successfully remove'}) return response({'message':'user not found'},status = status.HTTP_400_BAD_REQUEST)
def user_detail_api_view(request, pk=None): #queryset user = User.objects.filter(id=pk).first() #validation if user: #retrieve if request.method == 'GET': user_serializer = UserSerializer(user) return Response(user_serializer.data, status=status.HTTP_200_OK) #update elif request.method == 'PUT': user_serializer = UserSerializer(user, data=request.data) if user_serializer.is_valid(): user_serializer.save() return Response({'message': 'se actualizaron los datos'}, status=status.HTTP_200_OK) return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) #delete elif request.method == 'DELETE': user.delete() return Response({'message': 'Usuario eliminado correctamente!'}, status=status.HTTP_200_OK) return Response( {'mesagge': 'no se ah encontrado a un usuario con esos datos'}, status=status.HTTP_400_BAD_REQUEST)
def user_detail_api_view(request, pk=None): # consulta user = User.objects.filter(id=pk).first() if request.user.is_authenticated: # validacion if user: # retrieve if request.method == 'GET': users_serializer = UserSerializer(user) return Response(users_serializer.data, status=status.HTTP_200_OK) # update elif request.method == 'PUT': users_serializer = UserSerializer(user, data=request.data) # users_serializer = UserSerializer(user, data=request.data) if users_serializer.is_valid(): users_serializer.save() return Response(users_serializer.data, status=status.HTTP_200_OK) return Response(users_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # delete elif request.method == 'DELETE': user.delete() return Response({'message': 'Usuario Eliminado correctamente!!'}, status=status.HTTP_200_OK) return Response({'message': 'No se ha encontrado un usuario con estos datos'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'message': 'Inicie Sesion!!'}, status=status.HTTP_400_BAD_REQUEST)
class ValidationSerializer(serializers.ModelSerializer): """Serializer for validations""" item = InventoryItemSerializer() validated_by = UserSerializer() class Meta: model = Validation fields = ('id', 'item', 'is_approved', 'date_validated', 'validated_by', 'stage')
class ProductDesignSerializer(serializers.ModelSerializer): """Serializer for product design model""" dimensions = DimensionSerializer(many=True) images = ImageSerializer(many=True) drawings = DrawingSerializer(many=True) bill_of_materials = BillOfMaterialSerializer(source='billofmaterial_set', many=True) components = ComponentSerializer(source='parent_product', many=True) designers = UserSerializer(many=True, read_only=True) created_by = UserSerializer() modified_by = UserSerializer() class Meta: model = ProductDesign fields = ('sku', 'name', 'collection', 'category', 'year', 'variance', 'color', 'size', 'shape', 'dimensions', 'images', 'drawings', 'bill_of_materials', 'designers', 'components', 'date_created', 'date_modified', 'created_by', 'modified_by') def create(self, validated_data): product_design = ProductDesign.objects.create(**validated_data) # Create images images_data = validated_data.pop('images') for image_data in images_data: Image.objects.create(product=product_design, **image_data) # Create drawings drawings_data = validated_data.pop('drawings') for drawing_data in drawings_data: Drawing.objects.create(product=product_design, **drawing_data) # Create bill of materials bill_of_materials_data = validated_data.pop('bill_of_materials') for bill_of_material_data in bill_of_materials_data: BillOfMaterial.objects.create(product=product_design, **bill_of_material_data) return product_design
class MiniProductDesignSerializer(serializers.ModelSerializer): """Mini serializer for product design model""" dimensions = DimensionSerializer(many=True) images = ImageSerializer(many=True) drawings = DrawingSerializer(many=True) bill_of_materials = BillOfMaterialSerializer(source='billofmaterial_set', many=True) designers = UserSerializer(many=True, read_only=True) class Meta: model = ProductDesign fields = ('sku', 'name', 'collection', 'category', 'year', 'variance', 'color', 'size', 'shape', 'dimensions', 'images', 'drawings', 'bill_of_materials', 'designers')
def user_api_view(request): if request.method == 'GET': users = User.objects.all() users_serializer = UserSerializer(users, many = True) return Response(users_serializer.data) elif request.method == 'POST': user_serializer = UserSerializer(data=request.data) if user_serializer.is_valid(): user_serializer.save() return Response(user_serializer.data) return Response(user_serializer.errors)
def user_api_view(request): # list if request.method == 'GET': # queryset users = User.objects.all() users_serializer = UserSerializer(users, many=True) return Response(users_serializer.data, status=status.HTTP_200_OK) # create elif request.method == 'POST': user_serializer = UserSerializer(data=request.data) # validation if user_serializer.is_valid(): user_serializer.save() return Response({'message': 'Usuario creado correctamente!'}, status=status.HTTP_201_CREATED) return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def user_detail_api_view(request, pk=None): # queryset user = User.objects.filter(id=pk).first() # valitation if user: # retrive if request.method == 'GET': user_serializer = UserSerializer(user) return Response(user_serializer.data, status=status.HTTP_200_OK) # update elif request.method == 'PUT': """ en la siguiente línea: le pasamos el usuario en la db y la data que ingresa el usuario para que lo compare y actualize lo diferente """ # EXPLICITO: user_serializer = TestUserSerializer(instance = user, data=request.data) Es lo mismo que abajo: user_serializer = UserSerializer(user, data=request.data) if user_serializer.is_valid(): user_serializer.save() return Response(user_serializer.data, status=status.HTTP_200_OK) return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # delete elif request.method == 'DELETE': user.delete() return Response( {'message': 'El usuario ha sido eliminado con éxito.'}, status=status.HTTP_200_OK) return Response( {'message': 'No se ha encontrado un usuario con estos datos.'}, status=status.HTTP_400_BAD_REQUEST)
def user_api_view(request, ): # List if request.method == 'GET': # queryset users = User.objects.all() users_serializer = UserSerializer(users, many=True) # # hacemos un diccionario para pasarlo como data para hacer un usuario de prueba # test_data={ # 'name': "seba", # 'email': '*****@*****.**', # } # # serializamos la info con la clase que creamos en serializers # test_user = UserSerializer(data=test_data) # # si pasa la validación imprimimos un mensaje.>> Se guarda la data en validated_data # # pero si no lo pasa, crea un diccionario llamado "errors" que luego lo podemos imprimir. # if test_user.is_valid(): # user_instance = test_user.save() # print("Pasó las validaciones") # else : # print(test_user.errors) return Response(users_serializer.data, status=status.HTTP_200_OK) # Create elif request.method == 'POST': # queryset user_serializer = UserSerializer(data=request.data) # validation if user_serializer.is_valid(): user_serializer.save() return Response( {'message': 'El usuario ha sido creado con éxito.'}, status=status.HTTP_201_CREATED) # Si hay un error se auto genera un atributo 'errors' en el serializer, como en los forms. return Response(user_serializer.errors)