Skip to content

Instantly share code, notes, and snippets.

@Iftakharpy
Last active August 30, 2021 04:59
Show Gist options
  • Save Iftakharpy/337cb4a54b81d534b4732a160da94a37 to your computer and use it in GitHub Desktop.
Save Iftakharpy/337cb4a54b81d534b4732a160da94a37 to your computer and use it in GitHub Desktop.
How to add Tailwind CSS to your Django project

Requirements

  • Install Node.js and npm
  • Install Django with pip

Steps

  1. Start Django project
    django-admin startproject mysite
    
  2. Change working directory to the project directory
    cd mysite
    
  3. Start a new app
    python manage.py startapp myapp
    
  4. Create directory for static files
    • For Linux
      mkdir static/css/tailwind
      
    • For windows
      mkdir static\css\tailwind
      
  5. Edit settings of your django project. Don't forget to remove or comment out 'django.contrib.staticfiles', line in INSTALLED_APPS. Add your apps and STATIC_ROOT.
    File: mysite/settings.py
    import os
    
    ...
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        # 'django.contrib.staticfiles',
    
        # created apps
        'myapp',
    ]
    
    ...
    
    STATIC_URL = '/static/'
    STATIC_ROOT = BASE_DIR / 'static'
    
    STATIC_FILES_DIRS = [
        os.path.join(BASE_DIR, 'static'),
        BASE_DIR / 'static',
        ...
    ]
  6. Add url and document root to mysite/urls.py file.
    ...
    from django.contrib import admin
    from django.urls.conf import include    
    from django.urls import path
    
    # static
    from django.conf import settings
    from django.conf.urls.static import static
    
    ...
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('myapp.urls'))
    
        ...
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
  7. To use TailwindCSS in a django template follow the structure. File path myapp/templates/myapp/home.html
    {% load static %}
    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Document</title>
            <!-- load tailwind css -->
            <link rel="stylesheet" href="{% static 'css/tailwind/style.min.css' %}">
        </head>
        <body>
            <h1 class="text-8xl bg-gray-900">Hello world</h1>
        </body>
    </html>
  8. Don't forget to add views to your views.py and then add the view to your urls.py file.
    File: myapp/views.py
    # views.py
    
    from django.shortcuts import render
    
    # Create your views here.
    def home(request):
        return render(request, 'myapp/home.html')
    File: myapp/urls.py
    # urls.py
    
    from django.urls import path
    
    #views
    from .views import home
    
    urlpatterns = [
        path('', home)
    ]
  9. Create directory for tailwind
    mkdir jsTailwind && cd jsTailwind
    
  10. Init the directory as npm project
    npm init -y
    
  11. Install requirements for Tailwind CSS
    npm install tailwindcss autoprefixer clean-css-cli
    
  12. Setup Tailwind CSS
    npx tailwindcss init -p
    
  13. Add build script
    {
        ...
        scripts: {
            "build": "tailwind build ../static/css/tailwind/tailwind.css -o ../static/css/tailwind/style.css && cleancss -o ../static/css/tailwind/style.min.css ../static/css/tailwind/style.css"
            }
        ...
    }
    Here tailwind build tailwind.css -o style.css generates the CSS file using tailwind.css as entry point and cleancss -o style.min.css style.css generates minified CSS file using style.css as input file.
  14. Configure tailwind.config.js file details. Purge css documentation.
    module.exports = {
        future: {
            removeDeprecatedGapUtilities: true,
            purgeLayersByDefault: true,
        },
    
        darkMode: 'media', //to enable set 'media' or 'class'
    
        purge: {
            enabled: false, //true for production build
          
            //analyze files
            content: [
                '../**/*.html',
                // '../**/*.js',
            ],
          
            // css files
            css: [
                '../css/custom-style.css'
            ],
    
            //include selectors('.random', '#yep', 'button', regex: '^nav-') in the production build
            safelist: ['random', 'yep', 'button', /^nav-/],
            //exclude selectors from production build
            blocklist: ['usedClass', /^nav-/],
    
            //remove all unused styles
            mode: 'all',  
            preserveHtmlElements: false,
          
            // These options are passed through directly to PurgeCSS
            options: {
                keyframes: true,
                fontFace: true,
                variables: true
            },
        },
    
        theme: {
            extend: {},
        },
        variants: {},
        plugins: [],
    }
  15. Make tailwind entry point. In static/css/tailwind directory create tailwind.css file and copy paste the following layers.
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
  16. To build for production edit jsTailwind/tailwind.config.js set purge.enabled = true and run the command while you are in static/css/tailwind directory. For development set purge.enabled = false in jsTailwind/tailwind.config.js file.
    npm run build
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment