Django and Tailwind CSS: A Powerful Combination for Web Development

Learn how to use Django and Tailwind CSS to create beautiful, responsive, and functional web applications with ease. Streamline development with Flowbit.

image description

Django and Tailwind CSS: A Powerful Combination for Web Development

Learn how to use Django and Tailwind CSS to create beautiful, responsive, and functional web applications with ease. Streamline development with Flowbit.

Tailwind CSS is a popular utility-first CSS framework that can be used in a Django project to quickly and easily add styling to your website.

This guide will demonstrate how to set up a Django project with the integration of Tailwind CSS and Flowbite, which will enable you to develop modern web applications quickly and efficiently. Django is an open-source web framework that follows the model-template-views architecture and is built using Python.

The framework is currently maintained by the Django Software Foundation and is widely used by small and large corporations such as YouTube, Spotify, Instagram, Disqus, and Dropbox. With the increasing demand for Django developers, learning how to use this framework with Tailwind CSS and Flowbite is a valuable skill.

To fully utilize the component library and create a new Django project with Tailwind CSS and Flowbite, ensure you have Node.js and Python installed on your local machine. Then, follow the official Django installation guide or use the command 'python -m pip install Django' in the terminal to install Django.

python -m pip install Django

With the necessary technologies installed, you can now proceed to creating a new Django project.

Create a new project #

  1. Run the following command in the terminal to create a new Django project with the name myapp:

django-admin startproject myapp cd myapp/
  1. Create a new templates/ directory inside the project folder and update settings.py folder:

TEMPLATES = [ { ... 'DIRS': [BASE_DIR / 'templates'], # new ... }, ]
  1. Install django-compressor by running the following command in your terminal:

python -m pip install django-compressor
  1. Add compressor to the installed apps inside the settings.py file:

# config/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'compressor',  # new
]
  1. Configure the compressor inside the settings.py file:

COMPRESS_ROOT = BASE_DIR / 'static'

COMPRESS_ENABLED = True

STATICFILES_FINDERS = ('compressor.finders.CompressorFinder',)
  1. Create two new folders and an input.css file inside the static/src/ folder:

static
└── src
    └── input.css
  1. Create a new views.py file inside myapp/ next to urls.py and add the following content:

from django.shortcuts import render

def index(request):
    return render(request, 'index.html')
  1. Import the newly created view instance inside the urls.py file by adding the following code:

from .views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index, name='index')
]
  1. Create a new _base.html file inside the templates/ directory:

<!-- templates/_base.html -->

{% load compress %}
{% load static %}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Django + Tailwind CSS + Flowbite</title>

    {% compress css %}
    <link rel="stylesheet" href="{% static 'src/output.css' %}">
    {% endcompress %}

</head>

<body class="bg-green-50">
    <div class="container mx-auto mt-4">
        {% block content %}
        {% endblock content %}
    </div>
</body>

</html>

 

  1. Create an index.html file that will be served as the homepage:

<!-- templates/index.html -->

{% extends "_base.html" %}

{% block content %}
  <h1 class="text-3xl text-green-800">Django + Tailwind CSS + Flowbite</h1>
{% endblock content %}
  1. Finally, create a local server instance by running the following command:

python manage.py runserver
  1. You will now get an error that the output.css file does not exist, but that will be fixed once we install Tailwind CSS.

Now you have a working Django project locally. Let’s continue by installing Tailwind CSS.

Install Tailwind CSS #

  1. Run the following command the install Tailwind CSS as a dev dependency using NPM:

npm install -D tailwindcss

  1. Using the Tailwind CLI create a new tailwind.config.js file:

npx tailwindcss init
  1. Configure the template paths using the content value inside the Tailwind configuration file:

module.exports = {
  content: [
      './templates/**/*.html'
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
  1. Import the Tailwind CSS directives inside the input.css file:

/* static/src/input.css */

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
  1. Create a script inside the package.json file to build the final stylesheet:

{
  "scripts": {
    "build:css": "postcss static/src/input.css -o static/src/output.css"
  }
}
  1. Build the final stylesheet by running the following command:

npm run build:css
  1. And you're all set, your Django application is now using Tailwind CSS!

OR :

Run the following command to watch for changes and compile the Tailwind CSS code:

With Django and Tailwind CSS properly configured, you can now set up Flowbite to gain access to a wide array of interactive components such as navbars, modals, dropdowns, buttons, and more, streamlining the development process.

To install Flowbite and access its collection of interactive components, such as navbars, modals, dropdowns, and buttons, follow these steps:

  1. Install Flowbite as a dependency using NPM:

npm install flowbite
  1. Require Flowbite as a plugin inside the tailwind.config.js file:

module.exports = {

    plugins: [
        require('flowbite/plugin')
    ]

}
  1. Include Flowbite inside the content value of the tailwind.config.js file:

module.exports = {
  content: [
      './templates/**/*.html',
      './node_modules/flowbite/**/*.js'
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
  1. Include Flowbite’s JavaScript file inside the _base.html file just before the end of the<body> tag using CDN or by including it directly from the node_modules/ folder:

<script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/1.6.3/flowbite.min.js"></script>

With Flowbite installed, you can now search for and use its interactive components, such as navbars, modals, buttons, datepickers, and more.

To add a Navbar component inside the _base.html file, you can use the flowbite-navbar class, like this:

<header class="flowbite-navbar">
    <!-- Navbar content -->
</header>

Flowbite components :

Discover and utilize the interactive components from Flowbite by adding the Navbar component to the _base.html file as an example, using the flowbite-navbar class:

<!-- templates/_base.html -->

{% load compress %}
{% load static %}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Django + Tailwind CSS + Flowbite</title>

    {% compress css %}
    <link rel="stylesheet" href="{% static 'src/output.css' %}">
    {% endcompress %}

</head>

<body class="bg-green-50">

    <!-- Add this -->
    <nav class="bg-green-50 border-gray-200 px-2 sm:px-4 py-2.5 rounded dark:bg-gray-800">
        <div class="container flex flex-wrap items-center justify-between mx-auto">
          <a href="{{ .Site.Params.homepage }}/" class="flex items-center">
              <img src="/docs/images/logo.svg" class="h-6 mr-3 sm:h-9" alt="Flowbite Logo" />
              <span class="self-center text-xl font-semibold whitespace-nowrap dark:text-white">Flowbite Django</span>
          </a>
          <button data-collapse-toggle="mobile-menu" type="button" class="inline-flex items-center p-2 ml-3 text-sm text-gray-500 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600" aria-controls="mobile-menu" aria-expanded="false">
            <span class="sr-only">Open main menu</span>
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"></path></svg>
            <svg class="hidden w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>
          </button>
          <div class="hidden w-full md:block md:w-auto" id="mobile-menu">
            <ul class="flex flex-col mt-4 md:flex-row md:space-x-8 md:mt-0 md:text-sm md:font-medium">
              <li>
                <a href="#" class="block py-2 pl-3 pr-4 text-white bg-green-700 rounded md:bg-transparent md:text-green-700 md:p-0 dark:text-white" aria-current="page">Home</a>
              </li>
              <li>
                <a href="#" class="block py-2 pl-3 pr-4 text-gray-700 border-b border-gray-100 hover:bg-gray-50 md:hover:bg-transparent md:border-0 md:hover:text-green-700 md:p-0 dark:text-gray-400 md:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">About</a>
              </li>
              <li>
                <a href="#" class="block py-2 pl-3 pr-4 text-gray-700 border-b border-gray-100 hover:bg-gray-50 md:hover:bg-transparent md:border-0 md:hover:text-green-700 md:p-0 dark:text-gray-400 md:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">Services</a>
              </li>
              <li>
                <a href="#" class="block py-2 pl-3 pr-4 text-gray-700 border-b border-gray-100 hover:bg-gray-50 md:hover:bg-transparent md:border-0 md:hover:text-green-700 md:p-0 dark:text-gray-400 md:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">Pricing</a>
              </li>
              <li>
                <a href="#" class="block py-2 pl-3 pr-4 text-gray-700 hover:bg-gray-50 md:hover:bg-transparent md:border-0 md:hover:text-green-700 md:p-0 dark:text-gray-400 md:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent">Contact</a>
              </li>
            </ul>
          </div>
        </div>
      </nav>
    <!-- End of new HTML -->

    <div class="container mx-auto mt-4">
        {% block content %}
        {% endblock content %}
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/1.6.3/flowbite.min.js"></script>
</body>

</html>

"By adding the flowbite-navbar class, you can now have a functional and responsive navigation bar on all pages. To add more content directly to the view templates, not just the base template, use one of Flowbite's Card components.

For example, add the Card component to the index.html file:

<div class="flowbite-card">
    <!-- Card content -->
</div>

OR: 

<!-- templates/index.html -->

{% extends "_base.html" %}

{% block content %}

<h1 class="mb-6 text-3xl text-green-800">Django + Tailwind CSS + Flowbite</h1>
<div class="max-w-sm bg-white border border-gray-200 rounded-lg shadow-md dark:bg-gray-800 dark:border-gray-700">
    <a href="#">
        <img class="rounded-t-lg" src="/docs/images/blog/image-1.jpg" alt="" />
    </a>
    <div class="p-5">
        <a href="#">
            <h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">Noteworthy technology
                acquisitions 2021</h5>
        </a>
        <p class="mb-3 font-normal text-gray-700 dark:text-gray-400">Here are the biggest enterprise technology
            acquisitions of 2021 so far, in reverse chronological order.</p>
        <a href="#"
            class="inline-flex items-center px-3 py-2 text-sm font-medium text-center text-white bg-green-700 rounded-lg hover:bg-green-800 focus:ring-4 focus:outline-none focus:ring-green-300 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800">
            Read more
            <svg class="w-4 h-4 ml-2 -mr-1" fill="currentColor" viewBox="0 0 20 20"
                xmlns="http://www.w3.org/2000/svg">
                <path fill-rule="evenodd"
                    d="M10.293 3.293a1 1 0 011.414 0l6 6a1 1 0 010 1.414l-6 6a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-4.293-4.293a1 1 0 010-1.414z"
                    clip-rule="evenodd"></path>
            </svg>
        </a>
    </div>
</div>

{% endblock content %}

Now that you have integrated Django, Tailwind CSS, and Flowbite, you can take advantage of a wide range of interactive components to simplify and expedite the development of user interfaces.

Explore the full range of components by browsing the menu on the left sidebar under the “components” section, you will find many powerful and reusable components that will help you to build your application faster.

For more information on integrating Flowbite with Django, you can refer to the official Flowbite documentation at https://flowbite.com/docs/getting-started/django/

Note: These steps are a general guide, depending on your specific use case, additional configuration or steps may be needed.

 

DigitalOcean Referral Badge

DigitalOcean Sign Up : If you don't have a DigitalOcean account yet, you can sign up using the link below and receive $200 credit for 60 days to get started: Start your free trial with a $200 credit for 60 days link below: Get $200 free credit on DigitalOcean ( Note: This is a referral link, meaning both you and I will get credit.)


Latest From PyDjangoBoy

👩💻🔍 Explore Python, Django, Django-Rest, PySpark, web 🌐 & big data 📊. Enjoy coding! 🚀📚