Monday, April 21, 2025

How to Create and Map a System User in AEM (Step-by-Step Guide)

 In Adobe Experience Manager (AEM), when you build services or backend logic, you often need to access JCR (Java Content Repository) securely. For this, you don’t use regular users—you use System Users.





System Users are special, non-login users used for service-level operations. They don’t have passwords and are safer to use than admin or normal users.

Let’s walk through the steps to create and map a system user in AEM.


Step 1: Create a System User

  • Go to AEM Web Console: http://localhost:4502/crx/explorer/index.jsp
  • Log in with admin credentials.
  • Click on User Administration tab.



  • Click Create System User, and fill:
  • User ID: inowate-test-user
  • Add path. Click Create.(Under /home/system, create a folder for your project if not already created (example: /home/system/myproject). else you can create directly in system)
Note:  I'm assigning permissions to this folder because my contact form submissions will be stored in the JCR under this location. In your case, you should grant permissions to the folder where you intend to read, write, update, delete, or modify JCR nodes, depending on your specific requirements.


Check following screenshot from my practical work




Step 2: Assign Required Permissions

  • http://localhost:4502/useradmin
  • Search your system user: inowate-test-user
  • Select the user, and assign read/write permissions to specific paths your service will access. For example: (/content/myproject, /var/contact-form-submission)

Avoid giving unnecessary permissions. Check the following screenshot



Step 3: Map the User with a Service

  • http://localhost:4502/system/console/configMgr
  • search (Apache Sling Service User Mapper Service Amendment)
  • Add an entry like the following screenshot.


User System user in code

Now we can use system user in our code in servlet or in service where it required as per need
@Reference
private ResourceResolverFactory resolverFactory;

private ResourceResolver getServiceResourceResolver() {
    Map<String, Object> param = new HashMap<>();
    param.put(ResourceResolverFactory.SUBSERVICE, "my-service-name");
    try {
        return resolverFactory.getServiceResourceResolver(param);
    } catch (LoginException e) {
        log.error("Failed to get service resource resolver", e);
    }
    return null;
}


Conclusion

System users make your AEM services secure and clean. Just remember:

  • Create under /home/system
  • Use mapper config correctly
  • Give minimum permissions
  • Use getServiceResourceResolver() in your code



Wednesday, April 16, 2025

Getting Started with Django: Templates, Static Files, URLs, Views, and More

Getting Started with Django: Templates, Static Files, URLs, Views, and More






If you're new to Django, this post will walk you through some of the foundational concepts that are essential to building a Django project—from managing HTML templates and static files to handling routes, dynamic data, and user authentication.

Let’s break everything down step by step.

.


🧱 1. Templates: Where HTML Lives

In Django, if you want to create webpages using HTML, you store your HTML files inside a folder named templates.

Why?
Django uses its own templating engine to render HTML dynamically. So, keeping your HTML files in a dedicated templates folder is a best practice.

Example structure:

myapp/ ├── templates/ │ └── index.html

After this you add templates folder name in Templates oobject in  settings.py file like this 

        'DIRS': [BASE_DIR,"./templates"],

🎨 2. Static Files: CSS, JS, Images

Static files refer to your CSS, JavaScript, images, or any fonts that don’t change frequently.

To manage these in Django, you create a static folder:

Example structure:

myapp/ ├── static/ │ ├── css/style.css │ ├── js/script.js │ └── images/

In your HTML file, use Django’s {% load static %} tag to access them:

{% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}">

🖼️ 3. Media Files: User-Uploaded Content

All Static Media files are uploaded by users—like profile pictures, documents, or any other dynamic content.

To store these files, Django uses a media folder, and you need to configure it in your settings.py:


⚙️ 4. The settings.py File

Django's settings.py is the brain of your project. It controls:

  • Database configuration

  • Installed apps

  • Static and media file paths

  • Middleware

  • Templates configuration

  • Security settings

You’ll often come back to this file when changing configurations or integrating third-party apps.
 

🚀 5. Running the Django Project

Once your setup is ready and you've created your app, you can start the development server to run your Django project locally.

Use this command:

python manage.py runserver

By default, the server runs at http://127.0.0.1:8000/ — just open it in your browser to see your project live!

🧪 6. Migrations: Creating Database Tables

To create tables in the database (based on models you define), you use Django’s migration system.

Run this command:

python manage.py migrate

This applies all the built-in or custom model changes to your database. It's like syncing your database with your models.

👮 7. Creating a Superuser (Admin Panel)

Django has a built-in admin panel. To access it, you need a superuser account.

Create it using this command:

python manage.py createsuperuser

Fill in the username, email, and password. Then you can log into /admin and manage your data via an intuitive UI.

To go on admin dashboard you write /admin on after IP address then you can see your admin dashboard


📍 8. Routing in Django

In Django, routing means connecting a URL to a view function.

➕ Static Routes

  1. Create a function in views.py:

from django.http import HttpResponse
def aboutUs(request): return HttpResponse("Hello world")
  1. Add it in urls.py:

from django.urls import path from myproject import views myproject means your pproject folder name where you add your settings.py file urlpatterns = [ path('about-us/', views.aboutUs), ]

🔁 Dynamic Routes

Django allows you to create dynamic URL patterns to capture and use data directly from the URL.

You can define the type of data expected in the route using converters.

There are three commonly used types:

1. int → Accepts only integers
path('about/<int:courseid>/', views.courseDetail)
Example URL: /about/123/s

2. str → Accepts any non-empty string (excluding slashes)
path('about/<str:courseid>/', views.courseDetail)
Example URL: /about/python/

3. slug → Accepts letters, numbers, underscores, and hyphens
path('about/<slug:courseid>/', views.courseDetail)
Example URL: /about/hello-123/

Example View

Inside views.py, you can access the dynamic value like this:

from django.http import HttpResponse def courseDetail(request, courseid): return HttpResponse(f"Course ID is {courseid}")

This is useful for pages like course detail pages, product pages, blog posts, etc.

📦 9. Sending and Receiving Dynamic Data

Sometimes you want to send data from views to templates.

In views.py:

def homepage(request):
data = { "title": "Home Page", "name": "Welcome to my Django website" } return render(request, "index.html", data)

In index.html, receive it like this:

<title>{{ title }}</title>
<h1>{{ name }}</h1>

🔗 9. Linking URLs in Templates

Django provides the {% url %} tag for safe and dynamic internal linking.

Make sure your route in urls.py has a name:

path('about/<int>/', views.courseDetail, name='about')

Then in your template:

<a href="{% url 'about' %}">About</a>

🕵️ 10. Current Page Path

Want to know which page you're on?

In your template, you can use:

{{ request.path }}

This will return the current URL path, useful for active menu highlighting or logging.

🛠️ How to Create a Model in Django

Now we’ll walk through the steps to create a basic model in Django — from setting up your app to registering your model in the Django admin panel. Let's get started!

📁 Step 1: Create a New App

Before creating any models, you need to create a new Django app. In this example, we’ll call it service. Run the following command in your terminal: python manage.py startapp service This will generate a service folder with default files including models.py, admin.py, and more

✍️ Step 2: Define Your Model

Open service/models.py and define your model class. Here’s an example model for a service:

from django.db import models

class Service(models.Model): service_icon = models.CharField(max_length=50) service_title = models.CharField(max_length=50) service_des = models.TextField()

This creates a model with three fields: icon, title, and description.

🧱 Step 3: Create Migrations

Once the model is defined, generate the migration file that Django uses to create the corresponding database table:

python manage.py makemigrations

This will create a migration file under the migrations/ folder of your service app.

🗃️ Step 4: Apply Migrations

Now, apply the migration to actually create the table in your database:

python manage.py migrate

Your Service model is now part of the database!

⚙️ Step 5: Register the Model in Django Admin

To manage the Service model from the Django admin panel, register it in service/admin.py:

from django.contrib import admin

from service.models import Service class ServiceAdmin(admin.ModelAdmin): list_display = ('service_icon', 'service_title', 'service_des') admin.site.register(Service, ServiceAdmin)

This will show the service records with icon, title, and description columns in the Django admin dashboard.

Thursday, February 27, 2025

How to Use Adobe AEM SCSS in UI.Frontend: A Simple Guide


 When to Use UI.Frontend in AEM

Imagine you’re building a custom theme for an AEM site. Here’s how UI. Frontend helps:

Organized Code: Use the styles folder to manage SCSS files for your theme, like _variables.scss for colors and fonts.

Efficient Builds: The dist folder ensures your compiled CSS and JS are ready for deployment.

Dynamic Assets: Store static images in resources and dynamic ones in DAM.

Scalability: As your project grows, you can add more folders and files without clutter.


Benefits

Fast Loading: Compiled SCSS and JS in the dist folder to ensure optimized, minified code for faster page loads.

Organized Assets: Proper folder structure helps search engines crawl your site efficiently.

Reusable Components: Component-specific SCSS and JS make it easier to maintain and update your site.








Folder Structure in UI.Frontend

The folder structure is key to organizing your SCSS, JS, and other assets. Here’s a breakdown of how it works:

complete folder structure

1. UI.Frontend

This is the main folder created by default when you set up an AEM project. It’s where all your front-end code lives.

2. Dist Folder

The dist folder is important. When you build your project (using commands like npm run prod), your CSS and JS files are compiled and placed here. From dist, these files move to ui.apps/clientlibs/(your clientlibs name) and then get exported to the AEM server.

Pro Tip: If you delete the dist folder, don’t worry! Just run the build command again, and it will recreate the folder with all your compiled SCSS and JS files.

3. ProjectName Folder

Inside the src folder, you can create a separate folder (like projectName) to keep all your SCSS, JS, and assets organized. Alternatively, you can use the default components and resources folders. In the screenshot, I’ve created a separate folder for better organization.

4. JS Folder

The js folder is where you store all your JavaScript files. If you’re using packages like Bootstrap, you can either:

  • Install them via npm and reference them in package.json.
  • Download the files manually and place them in js/global/. Both approaches have their benefits:
  • npm approach: Easier to manage and update packages.
  • Manual download: More control over specific versions and no dependency on npm.
manage files in js


5. Resources Folder

Use the resources folder for static assets like images that won’t change often. For dynamic assets (images that might change), use the AEM DAM (Digital Asset Management) folder.
Example:

  • From resources: background: url("../resources/images/dotted-pattern.svg");
  • From DAM: background-image: url(/content/dam/your-folder/img/common/Plus.svg);

6. Styles Folder

The styles folder is where your SCSS files live. You can organize it further:

  • styles/base: For global files like _variables.scss or package files like _bootstrap.min.scss.
  • styles/components: For component-specific SCSS files.

You can create more folders inside styles as needed. (Points 6, 7, and 8 from the Main SS are addressed here.)

manage file in style

7. main.js + main.scss

These are the entry points for your project:

  • In main.scss, import all your SCSS files. Start with package files (if using downloaded packages) and then your custom SCSS files.
  • In main.js, import main.scss at the top, followed by all your JS files.

Examples

in main.scss import syntax

in main.jsimport syntax



Important Configuration Files

  1. clintlib.config.js 

This file is a configuration file for AEM Client Libraries (ClientLibs), using aem-clientlib-generator to manage JavaScript, CSS, and other assets for Adobe Experience Manager (AEM). Let’s go through it step by step:


// path: A Node.js module used to handle and manipulate file paths.
// { dependencies } = require("webpack"): Extracts dependencies from Webpack, but this isn't actually used later in the file.
const path = require("path");
const { dependencies } = require("webpack");


// BUILD_DIR: The output directory where Webpack compiles assets (dist as we discssued above it contain our all complied css+js).
// CLIENTLIB_DIR: The directory inside the AEM project where the ClientLibs are stored (/apps/projectname/clientlibs .
const BUILD_DIR = path.join(__dirname, "dist");
const CLIENTLIB_DIR = path.join(
__dirname,
"..",
"ui.apps",
"src",
"main",
"content",
"jcr_root",
"apps",
"projectName",
"clientlibs"
);


// 1. allowProxy: true: Allows accessing the client libraries via /etc.clientlibs/ instead of /apps/eti/clientlibs/.
// 2. serializationFormat: "xml": Defines the format for ClientLibs in AEM (used in .content.xml files).
// 3. cssProcessor: ["default:none", "min:none"]: Disables CSS minification.
// 4. jsProcessor: ["default:none", "min:none"]: Disables JavaScript minification.

const libsBaseConfig = {
allowProxy: true,
serializationFormat: "xml",
cssProcessor: ["default:none", "min:none"],
jsProcessor: ["default:none", "min:none"],
};

// context: BUILD_DIR: Sets the build directory as the working context.
// clientLibRoot: CLIENTLIB_DIR: Specifies the target directory inside AEM where the client libraries
module.exports = {
context: BUILD_DIR,
clientLibRoot: CLIENTLIB_DIR,

// libs: An array containing multiple ClientLibs definitions.
libs: [

// This defines a ClientLib named clientlib-dependencies:
// categories: ["eti.dependencies"]: Used to include this ClientLib in AEM components.
// cwd: "clientlib-dependencies": Looks for assets inside the clientlib-dependencies folder.
// files: ["**/*.js"], ["**/*.css"]: Copies all JavaScript and CSS files.
{
...libsBaseConfig,
name: "clientlib-dependencies",
categories: ["projectName.dependencies"],
assets: {
// Copy entrypoint scripts and stylesheets into the respective ClientLib
// directories
js: {
cwd: "clientlib-dependencies",
files: ["**/*.js"],
flatten: false,
},
css: {
cwd: "clientlib-dependencies",
files: ["**/*.css"],
flatten: false,
},
},
},

// Defines a ClientLib named clientlib-site:
// categories: ["eti.site"]: Used to load this ClientLib in AEM components.
// dependencies: ["eti.dependencies"]: Ensures that clientlib-dependencies is loaded first.
// Also includes non-JS/CSS files in resources, ignoring JS and CSS
{
...libsBaseConfig,
name: "clientlib-site",
categories: ["projectName.site"],
dependencies: ["projectName.dependencies"],
assets: {
// Copy entrypoint scripts and stylesheets into the respective ClientLib
// directories
js: {
cwd: "clientlib-site",
files: ["**/*.js"],
flatten: false,
},
css: {
cwd: "clientlib-site",
files: ["**/*.css"],
flatten: false,
},

// Copy all other files into the `resources` ClientLib directory
resources: {
cwd: "clientlib-site",
files: ["**/*.*"],
flatten: false,
ignore: ["**/*.js", "**/*.css"],
},
},
},


// Defines ClientLib clientlib-projectName:
// categories: ["projectName-site"]: Used in AEM components.
// dependencies: ["projectName.dependencies"]: Ensures dependent scripts load first.
// Similar to clientlib-site, it includes JS, CSS, and other assets.
{
...libsBaseConfig,
name: "clientlib-projectName",
categories: ["projectName-site"],
dependencies: ["projectName.dependencies"],
assets: {
// Copy entrypoint scripts and stylesheets into the respective ClientLib
// directories
js: {
cwd: "clientlib-projectName",
files: ["**/*.js"],
flatten: false,
},
css: {
cwd: "clientlib-projectName",
files: ["**/*.css"],
flatten: false,
},

// Copy all other files into the `resources` ClientLib directory
resources: {
cwd: "clientlib-projectName",
files: ["**/*.*"],
flatten: false,
ignore: ["**/*.js", "**/*.css"],
},
},
},
],
};




2. webpack.common.js

webpack.common.js is used to store shared configurations like entry points, output, and loaders.

"use strict";

// node.j plugin
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TSConfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const ESLintPlugin = require("eslint-webpack-plugin");

const SOURCE_ROOT = __dirname + "/src/main/webpack";

const resolve = {
extensions: [".js", ".ts"],
plugins: [
new TSConfigPathsPlugin({
configFile: "./tsconfig.json",
}),
],
};

module.exports = {
resolve: resolve,
// Defines the main entry file for your Project
entry: {
yourproject: SOURCE_ROOT + "/yourproject/main.js",
},

// Controls output structure (clientlib-yourproject/ vs clientlib-dependencies/)
// [name] dynamically gets replaced with the actual chunk name, so for the yourproject entry, Webpack generates:
// it will create file with this name inside dist like dist/clientlib-yourproject/yourproject.js
output: {
filename: (chunkData) => {
return chunkData.chunk.name === "dependencies"
? "clientlib-dependencies/[name].js"
: "clientlib-yourproject/[name].js";
},
path: path.resolve(__dirname, "dist"), // here we are point to dist folder as we discussed above
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader",
},
{
loader: "glob-import-loader",
options: {
resolve: resolve,
},
},
],
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
url: false,
},
},
{
loader: "postcss-loader",
options: {
plugins() {
return [require("autoprefixer")];
},
},
},
{
loader: "sass-loader",
},
{
loader: "glob-import-loader",
options: {
resolve: resolve,
},
},
],
},
],
},
resolve: {
alias: {
swiper: path.resolve(__dirname, "node_modules", "swiper"),
},
},
plugins: [
/* will clean old files from the dist folder before generating new ones.
The CleanWebpackPlugin automatically deletes files from the dist folder_
because Webpack's output.path defines where the build files go */
new CleanWebpackPlugin(),

// Checks code quality
new ESLintPlugin({
extensions: ["js", "ts", "tsx"],
}),

//MiniCssExtractPlugin extracts CSS into a separate file inside
//dist/clientlib-emoney/ so that AEM can use it as a client library.
new MiniCssExtractPlugin({
filename: "clientlib-yourproject/[name].css",
}),

/*This plugin copies static files (like images, fonts, etc.) from the
source folder (emoney/resources) to dist/clientlib-emoney/ so
they can be used in the final build.*/
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, SOURCE_ROOT + "/yourproject/resources"),
to: "./clientlib-yourproject/",
},
],
}),
],
stats: {
assetsSort: "chunks",
builtAt: true,
children: false,
chunkGroups: true,
chunkOrigins: true,
colors: false,
errors: true,
errorDetails: true,
env: true,
modules: false,
performance: true,
providedExports: false,
source: false,
warnings: true,
},
};


Conclusion

In conclusion, using UI.Frontend in AEM helps organize and manage front-end code efficiently. It ensures fast loading through optimized, minified CSS and JS files, and maintains a clear folder structure for scalability. Proper configuration files like `clintlib.config.js` and `webpack.common.js` further streamline the build process, making it easier to maintain and update the site.


Wednesday, January 29, 2025

WCAG Guide: How to Make Your Website Accessible to Everyone

Problem: 

The internet is a big part of our lives. We use it for work, school, shopping, and staying in touch with friends and family. But not everyone can use the web easily.

People with disabilities often face barriers that make it hard for them to access information and services online. This is where the Web Content Accessibility Guidelines (WCAG) come in.That’s where WCAG—the Web Content Accessibility Guidelines—comes in.






What is WCAG?

The Web Content Accessibility Guidelines (WCAG) are rules developed by the World Wide Web Consortium (W3C). These guidelines aim to make websites usable for everyone, including people with disabilities. WCAG focuses on four main areas:

1. Perceivable:

Content should be presented in ways people can notice, whether they’re using their eyes, ears, or touch.

2. Operable: 

Everyone should be able to navigate and interact with the website.

3. Understandable: 

Information should be easy to read and use.

4. Robust:

Websites should work with various devices, including assistive tools like screen readers.

Sunday, December 29, 2024

A Step-by-Step Guide to Adding Clientlibs to AEM Components and Working with SCSS | Adobe AEM

 Adobe Experience Manager (AEM) offers robust tools for developers to create highly customizable components. In this guide, we’ll show you how to add client libraries (clientlibs) to specific components in AEM and seamlessly integrate SCSS for styling. Let’s break it down step by step.



A Step-by-Step Guide to Adding
 Clientlibs to AEM Components and Working with SCSS

Structure of Component



How to Create a Component in AEM

Creating a component is the first step in building customized functionality in AEM. Here’s how you do it:

  1. Navigate to the desired folder where you want to create the component.
  2. Click on "Create" and select "Create Component from Dialog" from the dropdown menu.
  3. Fill in the details, such as:




  4. Click Next, and your component will be created.
  5. Rename the generated .jsp file to .html to use the HTL format for modern templating.




  6. Add a cq:dialog node for configuration:
    Click Create > Create Node, or
    Copy and paste the cq:dialog from an existing core component.
  7. Drag and drop your new component onto the page, and its contents will render.




How to Add Clientlibs to Specific Components in AEM

Client libraries are essential for adding styles and scripts to your AEM components. Follow these steps to create and link clientlibs:

1. Create the Clientlibs Folder

  1. Navigate to the component node in CRXDE Lite.
  2. Click on "Create" and select "Create Node".
  3. Name the node (e.g., clientlibs) and set its type to cq:ClientLibraryFolder.




2. Add Folders for CSS and JavaScript

  1. Inside the clientlibs folder:
    Create a folder named css and place all your CSS files inside.
    Create a folder named js and place all your JavaScript files inside.
  2. Add two files:
    css.txt: Import your CSS files (e.g., style.css).
    js.txt: Import your JS files (e.g., script.js).



3. Configure the Clientlibs Properties

  1. Select the clientlibs folder and add the following properties:
    categories: Assign a unique category name (e.g., mycomponent.styles).
    allowProxy: Set this to true for accessibility.

4. Include Clientlibs in Your HTML File

To link the clientlibs in your component, add the following code to your .html file:



code:

<sly data-sly-use.clientlib="/libs/granite/sightly/templates/clientlib.html">
    <sly data-sly-call="${clientlib.css @ categories='testScssClientlibs' }" />
</sly>
<h1 class="myClass">Test Scss Component is working</h1>
<sly data-sly-use.clientlib="/libs/granite/sightly/templates/clientlib.html">
   
    <sly data-sly-call="${clientlib.js @ categories='testScssClientlibs'}" />

</sly>

5. Verify Your Work

Reload your AEM page, and you should see your CSS and JS files successfully applied to the component.


How to Load Static Resources in a Component


To load static resources like images in AEM components, follow these steps:

  1. Create a folder named resources within your clientlibs directory.
  2. Place your images inside the resources folder.
  3. Use the path "/apps/emoney/components/site-components/TestScssCompo/test-scss-compo/clientlibs/resources/images/img1.png" to reference the image.
  4. This path can be used in both HTML and CSS files to load the image.





How to Use SCSS with AEM Components

For advanced styling, SCSS provides a cleaner and more maintainable approach compared to plain CSS. Here’s how to integrate SCSS into your AEM components.

1. Set Up Your Environment

  1. Install the VS Code AEM Sync extension for easy code management.

  2. Import your component from the AEM server:
    - Right-click the parent folder in VS Code.
    - Select "Import from Server".

  3. Install Sass globally using the following command:

    bash : npm install -g sass

2. Create and Compile SCSS

  1. Navigate to the css folder of your component.

  2. Create a new file named style.scss.

  3. Write your SCSS code and compile it to CSS with the following command:


    command : sass style.scss style.css
  4. The SCSS code will be converted to a style.css file, which is already linked to the component via clientlibs.

3. Export to AEM

After making changes, export the component back to AEM:

  1. Right-click your component in VS Code and select "Export to Server".
  2. Refresh the AEM page to see the updated styles.



Common Issues and Troubleshooting

Why Are My Clientlibs Not Loading?

  • Ensure that the allowProxy property is set to true.
  • Check that the categories name matches in both the clientlibs folder and your .html file.

How Can I Debug SCSS?

  • Use browser developer tools to inspect styles and ensure your compiled CSS is properly linked in css.txt.


Conclusion

This comprehensive guide covers everything you need to know about adding clientlibs to specific AEM components and integrating SCSS. By following these steps, you can build scalable, modular, and visually appealing components with ease.

If you found this guide helpful, don’t forget to share it with your peers. For more AEM tutorials and tips, bookmark this blog and stay updated!

Wednesday, December 25, 2024

Git Operations: A Comprehensive Guide | github

 

Git Operations: A Comprehensive Guide

Git is an essential tool for version control, widely used by developers. In this guide, we'll walk through common Git operations that every developer should know. Bookmark this page as we’ll continue adding more operations in the future.


Combine All Pushed Commits into One Method 1

To clean up your commit history and combine multiple commits into a single one, follow these steps:


1. Count the total commits on the live branch

command: git log 
description: this will show all the commits on git you just need to count where is your branch name

2. Rebase the last X commits:

command: git rebase -i HEAD~6

description: instead of 6 you need to write a number of commits that you found in step 1

3. Edit the commits A terminal console will appear with all the commits labeled "pick."

  • Press i to enter insert mode.
  • Replace the word pick with squash for all but not for the first commit.
  • 4. Save and exit:

    Press Esc, then type :wq and hit enter.

    5. Push the changes:

    git push origin your-branch-name --force 

    Combine All Pushed Commits into One Method.2(Recomanded)

    command: git log 
    description: this will show all the commits on git you just need to count where is your branch name

    • git reset --soft head~(number of commits)
    • git stash
    • git checkout master and delete your old branch
    • git pull in master
    • git checkout -b branch with same name that we deleted
    • git stash apply (then solve conflict if any)
    • git push with --force

    How to Fetch a Remote Branch to Local

    If you need to fetch a remote branch and work on it locally, follow these steps:

    Step No 01: Fetch the branch: 

    git fetch origin
    Step No 02: Check out the branch:
    git checkout branch-name-that-you-need-to-checkout
     

    How to Rename a Branch Locally

    Sometimes you might want to rename a local branch.Here's how you can do it:

    Step No 01: Checkout the branch you want to rename
    git checkout branch-name
    Step No 02: Rename the branch git branch -m new-branch-name
    Step No 03: Delete the old branch from the remote git push origin --delete old-branch-name
    Step No 04: Push the renamed branch to the remote git push origin new-branch-name
    Step No 05: Set the upstream for the new branch git push --set-upstream origin new-branch-name