HTMX, Tailwind CSS, and Django: Introduction and Setup. Part 1

Patryk Młynarek - Backend Engineer

Patryk Młynarek

30 January 2024, 8 min read

thumbnail post

What's inside

  1. Why Django with HTMX and Tailwind CSS?
  2. Setting Up Your Django Project
  3. Installing and Configuring HTMX
  4. Integrating Tailwind CSS
  5. How to Integrate Django with HTMX and Tailwind CSS Using Docker
  6. Conclusion

The right tech stack is more than just a toolkit - it’s the cornerstone of efficient and engaging web development. But with so many options, how do we pinpoint the standouts? Enter HTMX and Tailwind CSS.

  • HTMX: A library that unlocks access to AJAX, CSS Transitions, WebSockets, and Server-Sent Events directly in HTML. By leveraging attributes, it simplifies the creation of modern user interfaces, harnessing the power and elegance of hypertext.

  • Tailwind CSS: A utility-first CSS framework designed for the swift construction of modern websites, keeping you within the confines of your HTML.

Moving forward with our guide, we delve deep to reveal the synergies between Django, HTMX, and Tailwind CSS. Beginning with an insight into the core advantages of this tech combination, we transition into hands-on steps covering setup, styling, and flawless deployment, even exploring the domain of Docker containerization.

So, whether you are an experienced web developer or searching for the newest web trends, this guide is for you! And for those who prefer hands-on learning? We've prepared a ready-to-use testing project just for you! Check it out here.

Why Django with HTMX and Tailwind CSS?

Django, HTMX, and Tailwind CSS come together as a powerful trio, offering a range of compelling reasons for their adoption. Here, we explore why this combination is worth your consideration:

  • Efficiency and Productivity: Django's high-level framework, combined with HTMX's streamlined interactions and Tailwind CSS's utility-first approach, accelerates development without sacrificing quality.
  • Seamless Integration: Django's adaptability seamlessly accommodates HTMX and Tailwind CSS, ensuring a harmonious development process.
  • Interactive User Experiences: HTMX empowers dynamic, user-centric web applications with minimal code complexity, enhancing engagement.
  • Minimal Front-End Complexity: HTMX simplifies front-end development, reducing JavaScript complexities and maintaining code cleanliness.
  • Rapid Prototyping: The trio enables swift idea iteration, concept testing, and application refinement with minimal overhead.
  • Efficient Styling: Tailwind CSS's utility classes facilitate easy, customizable styling, maintaining design consistency.
  • Performance Optimization: HTMX minimizes data transfer and load times, while Tailwind CSS optimizes production-ready CSS files for swift loading.
  • Community and Resources: Active communities and abundant resources support the development journey.
  • Versatile Use Cases: Ideal for projects of all scales, from blogs to complex web applications, it offers versatility and adaptability.
  • Future-Proof Development: Embracing modern development trends, it provides a solid foundation for evolving projects as technologies advance.

Setting Up Your Django Project

Before setting up your Django project, ensure that you have Python 3 and the Django package installed on your system.

This command installs your system's Django package from the Python Package Index (PyPI).

pip install django

Once you have Python 3 and Django installed, you can create your Django project. To initiate a new project, open your terminal or command prompt, navigate to the directory where you want to create your project, and run:

python manage.py startproject myproject

Replace myproject with the name you want for your project. This command creates a new Django project with the specified name in your current directory.

Installing and Configuring HTMX

Resource: HTMX Documentation

To set up HTMX for your project, you have several installation options. Choose the one that best fits your development needs:

Via a CDN (e.g., unpkg.com)

The quickest way to start using HTMX is to load it via a Content Delivery Network (CDN). Simply add the following script tag to the section of your HTML file:

<script src="https://unpkg.com/htmx.org@1.9.6" integrity="sha384-FhXw7b6AlE/jyjlZH5iHa/tTe9EpJ1Y55RjcgPbjeWMskSxZt1v9qkxLJWNJaGni" crossorigin="anonymous"></script>

While the CDN approach is simple and convenient for getting started, it's worth considering whether to use CDNs in a production environment.

Download a Copy

Another straightforward method to install HTMX is to download and include it in your project directly. Follow these steps:

  1. Download htmx.min.js from unpkg.com.
  2. Place it in the appropriate directory within your project.
  3. Include it in your HTML using a script tag:
<script src="/path/to/htmx.min.js"></script>

Via npm

For projects using npm-style build systems, you can install HTMX via npm:

npm install htmx.org

After installation, you'll need to integrate it into your build process. This typically involves referencing node_modules/htmx.org/dist/htmx.js (or htmx.min.js) in your project. You may also bundle HTMX with any extensions and project-specific code as needed.

Via Webpack

If you're utilizing Webpack to manage your JavaScript, follow these steps:

  1. Install HTMX via your preferred package manager (e.g., npm or yarn).
  2. Import HTMX into your index.js file.
  3. If you intend to use the global htmx variable (recommended), inject it into the window scope by creating a custom JavaScript file.
  4. Import this custom JavaScript file into your index.js, placing it below the import from step 2.
  5. Rebuild your bundle to apply the changes.

By choosing one of these installation methods, you'll be ready to integrate HTMX into your project and harness its capabilities for creating dynamic and interactive web applications.

Integrating Tailwind CSS

Resource: Tailwind CSS Installation

When integrating Tailwind CSS, you have several options to match your specific development environment and preferences.

Tailwind CLI

The quickest and most straightforward way to kickstart your project with Tailwind CSS from the ground up is by using the Tailwind CLI tool. This command-line interface simplifies the setup process and is available as a standalone executable. If you prefer to work without Node.js, the standalone executable is an excellent choice.

npm install -D tailwindcss
npx tailwindcss init
npx tailwindcss -i ./src/input.css -o ./dist/output.css

Using PostCSS

To seamlessly integrate Tailwind CSS with popular build tools like webpack, Rollup, Vite, and Parcel, consider installing it as a PostCSS plugin. This approach ensures a smooth integration with your build workflow, making it an ideal choice for modern web development projects.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
postcss ...

Framework Guides

For specific development frameworks, you can refer to framework-specific guides. These guides provide tailored recommendations and best practices for integrating Tailwind CSS into various popular environments, ensuring an optimal setup that aligns with your framework of choice.

Check out the list here.

Play CDN

You can use the Play CDN if you're looking for a quick way to experiment with Tailwind CSS in your browser without going through an entire build process. It's a convenient option for development purposes, allowing you to test Tailwind CSS right in the browser. However, it's essential to note that the Play CDN is unsuitable for production use.

<script src="https://cdn.tailwindcss.com"></script>

In the upcoming article about Django with HTMX and Tailwind CSS, we'll explore alternative installation methods, including the use of dedicated Django packages like django-htmx and django-tailwind for a seamless integration experience

How to Integrate Django with HTMX and Tailwind CSS Using Docker

To enable our project to run efficiently using Docker with the integration of Django, HTMX, and Tailwind CSS, we need to create a Docker image (Dockerfile) that includes all the essential components required for our application. These components encompass Django for web development, HTMX for interactive features, and Tailwind CSS for modern styling. A Docker Compose file is the cornerstone, unifying and synchronizing all these components for seamless operation.

Note: You can find a fully working example based on this Docker configuration in the linked repository.

Dockerfile

The Dockerfile consists of the following steps:

  1. Setting up Node.js and the npm package manager to manage frontend dependencies.
  2. Installing the Django package and any additional requirements for our project.
  3. Installing Tailwind CSS and HTMX.
  4. Generating a Tailwind CSS output file containing the styles we actively use.
  5. Copying HTMX scripts to the appropriate directory.
FROM python:3.11.5-slim

# Install Node.js and npm
RUN apt update && apt install -y nodejs npm

# Install requirements
ARG REQUIREMENTS_FILE=base.txt
ADD requirements/${REQUIREMENTS_FILE} requirements.txt
RUN pip install pip --upgrade && pip install -r requirements.txt

# Copy project
ADD /app /src/app
ADD /tailwindcss/ /src

# Install Tailwind CSS, HTMX and other dependencies
WORKDIR /src
RUN npm install tailwindcss htmx.org
RUN npm run build:tailwindcss
RUN npm run build:htmx

# Set final workdir
WORKDIR /src/app

# Command to run when image started
CMD python manage.py runserver 0.0.0.0:8000

Docker compose

Here's the Docker Compose configuration:

version: "3"

x-base-app-conf: &base_app_conf
    env_file: .env
    stdin_open: true
    tty: true

services:
    myproject:
        <<: *base_app_conf
        image: myproject:latest
        container_name: myproject
        restart: always
        build:
            context: .
            dockerfile: docker/Dockerfile
        ports:
            - "8000:8000"
        volumes:
            - "./app:/src/app"
        depends_on:
            - db

    # Generating CSS output file for Tailwind CSS on save
    npm-watch:
        <<: *base_app_conf
        image: myproject:latest
        container_name: npm-watch
        working_dir: /src
        command: npm run watch:tailwindcss
        restart: always
        volumes:
            - "./app:/src/app"
        depends_on:
            - myproject
    # Copying JS file from htmx package
    htmx-js-generator:
        <<: *base_app_conf
        image: myproject:latest
        container_name: htmx-js-generator
        working_dir: /src
        command: npm run build:htmx
        restart: no
        volumes:
            - "./app:/src/app"
        depends_on:
            - myproject

    db:
        image: postgres:16.0-alpine
        command: ["postgres", "-c", "log_statement=all", "-c", "log_destination=stderr"]
        container_name: db
        restart: always
        environment:
            - POSTGRES_DB=mydatabase
            - POSTGRES_USER=postgres
            - POSTGRES_PASSWORD=postgres
        ports:
            - "5432:5432"
        volumes:
            - db:/var/lib/postgresql/data
volumes:
    db:

Conclusion

The journey so far has equipped us with the knowledge and tools needed to combine Django, HTMX, and Tailwind CSS into a powerful development stack. We've set up our project, configured our technologies, and prepared for efficient deployment.

In the next part of our article, we'll delve deeper into the practical application of these technologies and explore real-world examples of how they work together seamlessly.

Stay tuned for the next installment in our journey!

Are you looking for expert assistance or have questions about this stack? Contact us for professional guidance and support!

Patryk Młynarek - Backend Engineer

Patryk Młynarek

Backend Engineer

Patryk is a experienced Senior Python Developer who puts business value on the first place. Web applications enthusiast from initial development to server maintenance, ensuring the entire process runs smoothly. In his free time, Patryk enjoys playing board games and motorcycling.

Tags

Django
Python
CSS

Share

Let's talk

Discover how software, data, and AI can accelerate your growth. Let's discuss your goals and find the best solutions to help you achieve them.

Hi there, we use cookies to provide you with an amazing experience on our site. If you continue without changing the settings, we’ll assume that you’re happy to receive all cookies on Sunscrapers website. You can change your cookie settings at any time.