Django and Tailwind (simple solution)

Feb. 12, 2023
Avatar
Author

If you want a simple solution to incorporating Tailwind to your Django project without feeling like you are breathing manually, this is the guide for you.

AD

I have split these instructions in 2 sections, Django set up and tailwind setup.

prerequisites:

  • you will need python installed
  • you need node js installed to run postcss

Django Set up

here we will set up the Django project you can skip this part if you have an existing Django project.

Note you can view the git repository here: https://github.com/Josh1st/Django-tailwind-simple its mainly just for reference but you could use it as long as you change the Django secret key and etc.

First we will create a python virtual environment and install Django, Create a Django project and an app. In your desired project directory run these commands:

    
# create python virtual environment
python -m venv env
env\Scripts\activate

# install and create a Django project
# if you have an existing Django project, you and obviously skip this step
pip install django
django-admin startproject app

# navigate to the Django project directory
cd app

# create the an app
python manage.py startapp home
    

Now we need to add some HTML that contains some tailwind classes in order to get any css out of postcss. We need to:

  • add a view to the app and add it to urls.py
  • add a template with HTML and some tailwind classes + include the CSS file that will be generated later πŸ˜‰
  • add "home" to installed apps in settings.py

You can skip this if you have an existing Django project

In app/home/views.py add the following:

    
# app/home/views.py
from django.http import HttpResponse
from django.template import loader
import datetime


def home(request):
    now = datetime.datetime.now()
    template = loader.get_template('home/index.html')
    context = {
        'now': now,
    }
    return HttpResponse(template.render(context, request))
    

in app/app/urls.py add the view:

    
# app/app/urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings # πŸ‘ˆ needed to access the settings in settings.py
from home.views import home # πŸ‘ˆ import the view
from django.conf.urls.static import static # πŸ‘ˆ needed for static files


urlpatterns = [
    path('', home), # πŸ‘ˆ add path to the view
    path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # πŸ‘ˆ add this so we can have static files
    

Now create the template in app/home/templates/home/index.html

    
<!-- app/home/templates/home/index.html -->
{% load static %} <!-- πŸ‘ˆ needed to load static files -->
<html>
    <head>
        <link rel="stylesheet" href="{% static 'styles.css' %}"> <!-- πŸ‘ˆ note .css not .scss -->
    </head>
    <body class='w-full min-h-screen bg-grid-slate-100 flex justify-center content-center items-center'>
        <div class="beans block border-2 rounded-md p-4 hover:p-6 hover:border-indigo-500 hover:ring-indigo-500 sm:text-sm"> <!-- πŸ‘ˆ note custom css class "beans" -->
            It is now {{now}}
        </div>
    </body>
</html>
    

Lastly in app/app/settings.py add the app to installed apps and add static files dirs.

    
# ...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',     # πŸ‘ˆ add the app
]
# ...

# (further down)
STATIC_URL = 'static/'

STATICFILES_DIRS = [
    BASE_DIR / "static",     # πŸ‘ˆ add the static directory
]
# ...
    

That's the Django side of things set up, you can follow on from here if you have an existing Django project.

Tailwind Set up

Now on to the meat πŸ₯© and potatoes πŸ₯” of this guide, we are going to go with bare bones approach to setting up tailwind so that it is as simple as possible, the main advantage of this approach is that it is not dependent on a Django tailwind plugin/app, it's simple and customizable.

First, we need to run some commands in the root directory:

    
# get back into the root directory if you are using the same shell from the above commands.
cd ..

# assuming you already have node + npm installed, init your node project
npm init -y

# Install tailwindcss and other dependencies via npm
npm install -D tailwindcss postcss autoprefixer postcss-import postcss-cli postcss-scss postcss-nesting
    

Create a "postcss.config.js" file in the root directory and paste these contents (source: https://tailwindcss.com/docs/using-with-preprocessors).

    
// postcss.config.js
module.exports = {
  plugins: {
    'postcss-import': {},
    'tailwindcss/nesting': 'postcss-nesting',
    tailwindcss: {
      // tailwind config goes here
      content: ["./app/**/*.{html,js}"], // πŸ‘ˆ this is important 
    },
    autoprefixer: {},
  }
}
    

Setting the content to this means it will search for any HTML and js files inside the app directory to find any CSS classes to make sure they are included, but also purge out all the unused CSS.

Now we need to create the static file setup. create a folder in the Project Directory called "static" and add a SCSS file in it and call it "styles.scss" (you can call it whatever you want just remember what you called it for later). In "styles.scss" add the following SCSS or whatever you want. You can put any CSS in here just make sure to add in the 3 tailwind imports.

    
// app/static/styles.scss
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

// add your own CSS here
.beans {
    background-color: aqua;
}
    

Now we can run an npx command to process our scss

    
npx postcss ./app/static/styles.scss -o ./app/static/styles.css -m --config ./postcss.config.cjs
    

Essentially this is all that is necessary, you should have a "styles.css" file in "app/static" but we can do more, what I like to do for each of my projects is create a one-click launcher, in the form of a batch file, so that I'm not running multiple commands to get a project started. let's take a look:

    
@REM run.bat
@REM this line forces the cmd to stay open on error so that you can diagnose problems
@REM source: https://stackoverflow.com/questions/17118846/how-to-prevent-batch-window-from-closing-when-error-occurs
if not defined in_subprocess (cmd /k set in_subprocess=y ^& %0 %*) & exit )

@REM create the CSS file
cmd /c "npx postcss ./app/static/styles.scss -o ./app/static/styles.css -m --config ./postcss.config.cjs"

@REM open vscode, activate the python env, cd into app, run migrations, run test server
cmd /k "code . && env\Scripts\activate.bat && cd app  && python manage.py makemigrations && python manage.py migrate && python manage.py runserver"


@REM pause the execution if any of the above failed otherwise the cmd will just close
pause
    

Double click that bad boy and it will generate your CSS, open vs code make plus run migrations and start the development server, what more could you need? πŸ˜‹

The only controversial thing here is that I run migrations every time I start the app which might lead to problems however I haven't run into many problems and the ones I did run into were just problems in my own code that needed fixing. but you can edit it to your liking.

Every time I need to refresh the CSS or run a migration I just close the batch execution and restart it.

That's it, you can work on it from here and customise this setup as much as you like.

AD
AD
Share this post:

Comments

Related Articles

All posts
Top