Using Bootstrap in web projects is one of the best ways to design fast and user-friendly interfaces. An excellent point about Bootstrap is that you can easily use it in your projects and benefit from its CSS classes and JavaScript libraries. In this article, we intend to examine how to add Bootstrap 5 to a Django project.
One of the ways to use Bootstrap in Django is to access its libraries via CDN. This method is the fastest and simplest way to integrate Bootstrap with your project.
You need to configure your HTML template file to link to the CSS and JS files of Bootstrap 5. For instance, you can modify your main template file as follows.
Following this approach, another way is to download Bootstrap’s files directly to your project and use them locally.
Sample Code
<!-- In the base.html file of your project -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project Using Bootstrap</title>
<!-- Link to Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-..." crossorigin="anonymous">
</head>
<body>
<h1>Hello World</h1>
<!-- Your page code -->
<!-- Bootstrap JavaScript files -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-..." crossorigin="anonymous"></script>
</body>
</html>
Line by Line Code Explanation
<!DOCTYPE html>
This line defines that the document is of type HTML5.
<html lang="en">
This tag specifies the root element of HTML and sets the language to English.
<meta charset="UTF-8">
This tag sets the character encoding for the HTML document to UTF-8.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
This tag configures the viewport for responsiveness, ensuring the page displays well on different devices.
<title>Project Using Bootstrap</title>
This sets the title of the web page which appears on the browser tab.
<link href="...">
Links to the CSS file from CDN to add Bootstrap styles to the page.
<h1>Hello World</h1>
This displays a header in the web page.
<script src="...">
This links to the JavaScript files from Bootstrap for interactive components to function on the page.