How to use TailwindCSS with Django?
Updated in July 2022: PostCSS is no longer necessary - there is a standalone CLI - django-browser-reload is the best extension - Django-tailwind plugin is an acceptable solution too.
There are (at least) 3 different methods to install Tailwind with Django properly.
1st method: NPM
This is the preferred method if you need node in your project (e.g : add plugins like Daisy UI, or have a SPA)
Installing tailwindCSS and build/minify processes
- Create a new directory within your Django project, in which you'll install tailwindCSS like in any vanilla JS project setup:
cd your-django-folder; mkdir jstoolchain; cd jstoolchain
npm init -y
npm install -D tailwindcss
npx tailwindcss init
- Configure your template paths in
tailwind.config.js
that have just been created, by specifying the right place to parse your content. This could be something like below or a little different, depending on where your templates are located:
...
content: ["../templates/**/*.{html,js}"],
...
- In
your-django-folder
, create aninput.css
file and add at least this in it:
@tailwind base;
@tailwind components;
@tailwind utilities;
- In your
package.json
file, you can prepare npm scripts to ease execution of build / minify tasks (adapt the paths according to your Djangostatic
folder location):
"scripts": {
// use in local environment
"tailwind-watch": "tailwindcss -i ../input.css -o ../static/css/output.css --watch",
// use in remote environment
"tailwind-build": "tailwindcss -i ../input.css -o ../static/css/output.css --minify"
}
In your
jstoolchains
folder, keep runningnpm run tailwind-watch
while you're coding. This will ensure that youroutput.css
file is regenerated as soon as you add a new tailwind class to your code. Add this file to.gitignore
.If
tailwind-watch
is running without error,output.css
file should now be filled with CSS. Now you can actually use tailwindCSS classes, by including the outputted css file into a Django template file along with Django's call to load the static files:
{% load static %}
<head>
<link rel="stylesheet" href="{% static "css/output.css" %}">
</head>
- Don't forget to include the
npm run tailwind-build
script in your deployment process. This will build the output and remove unused classes to ensure a lower file size.
Handling auto-reload locally
What's missing now to ease development, is to auto-reload the django development server when an HTML file is changed and saved.
The best extension to deal with this is Django-browser-reload.
Just follow setup instructions, this will work as expected out of the box
2nd method: standalone CLI
This is the preferred method if your project does not require node at all (eg: you don't have SPA for your front, you don't need plugins like daisyUI, etc.).
You can install it manually following the official instructions, or automate it using a script shell like this:
#!/bin/sh
set -e
TAILWIND_ARCHITECTURE=arm64 # chose the right architecture for you
TAILWIND_VERSION=v3.1.4 # chose the right version
SOURCE_NAME=tailwindcss-linux-${TAILWIND_ARCHITECTURE}
OUTPUT_NAME=tailwindcss
DOWNLOAD_URL=https://github.com/tailwindlabs/tailwindcss/releases/download/${TAILWIND_VERSION}/${SOURCE_NAME}
curl -sLO ${DOWNLOAD_URL} && chmod +x ${SOURCE_NAME}
mv ${SOURCE_NAME} ${OUTPUT_NAME} # rename it
mv ${OUTPUT_NAME} /usr/bin # move it to be used globally in a folder already in the PATH var
For Tailwind configuration itself, please refer to the 1st method where it's explained in detail.
3rd method: django-tailwind plugin
This plugin produces more or less the same results than you get manually with the npm method. The plugin is well documented, up to date, and people seem to be satisfied with it.
As a personal preference, I think abstractions like this creates a little too magic and I prefer building the toolchain by myself to know what's happening behind the scene.
But feel free to experiment this method as well and pick it if it suits you!
Django - TailwindCSS won't load some attributes
We finally managed to solve this issue.
The problem was that I ran python manage.py collectstatic
which created the following directory : static > css > dist > styles.css
. django-tailwind
created the same repository under the theme
folder. Every time I tried to restart the server, the wrong styles.css
was taken into account. So by changing the name of the first folder, it enabled me to load the correct CSS file.
Changing TailwindCSS class using Django and JS
You are calling the function get_id_transporter() when you click a button but the rest of the code is only runs once...when the page loads.
With the code above, var transporterId never gets set until a button is clicked. The code that uses transporterId (after if(button)
) has already run
If you change your expression to ${1} it works because button-transporter-1 is an actual ID. If you changed it to ${1+1} and button-transporter-2 was an actual id, it would work also.
There's maybe something a little funky about your logic. I suspect you don't want to add a click event listener after the button is clicked. In any event, you can just call the code that changes the class as part of your get_id_transporter() function eg,
<script>
function get_id_transporter(clickedId){
transporterId = clickedId;
numberTransporter = parseInt(transporterId.split("-")[2]);
modify_classes(numberTransporter)
}
function modify_classes(numberTransporter) {
document.getElementById(`container-button-transporter-${numberTransporter}`).className = "flex flex-row items-center justify-between p-2 bg-[#195266]";
document.getElementById(`button-transporter-${numberTransporter}`).className = "text-white";
}
</script>
Above I separated it out into another function and called it at the end of get_id_transporter, so it doesn't run until it's got something to work with.
Related Topics
How to Change an Image Size in Pygame
How to Generate an HTML Directory List Using Python
Getting Segmentation Fault Core Dumped Error While Importing Robjects from Rpy2
Python VS Groovy VS Ruby? (Based on Criteria Listed in Question)
Is There a Python Equivalent for Rspec to Do Tdd
Difference Between Multiple If's and Elif'S
Best Way to Find the Months Between Two Dates
How to Capture Multiple Camera Streams with Opencv
How to Send an Email with Python
How to Split a Multi-Line String into Multiple Lines
Understand the Find() Function in Beautiful Soup
How to Add Sum to Zero Constraint to Glm in Python
Ruby Equivalent of Python's "Dir"
The Simplest Possible Reverse Proxy
Get Protocol + Host Name from Url
MAC Osx Python Ssl.Sslerror: [Ssl: Certificate_Verify_Failed] Certificate Verify Failed (_Ssl.C:749)