[go: up one dir, main page]

Open In App

How to use Tailwind CSS with Django ?

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Tailwind CSS has gained immense popularity among developers for its utility-first approach to styling web applications. Django on the other hand is a robust and flexible web framework written in Python. Combining these two powerful tools can enhance your Django projects. In this article, we will explore how to integrate the capabilities of Tailwind CSS within a Django project.

Tailwind CSS is basically a Utility-first CSS framework for building rapid custom UI. It is a highly customizable, low-level CSS framework that gives you all of the building blocks that you need. Also, it is a cool way to write inline styling and achieve an awesome interface without writing a single line of your own CSS.

Python Django is a web framework that is used to create web applications very efficiently and quickly. Django is called a battery-included framework because it contains a lot of built-in features such as Django Admin Interface, default database – SQLite3, etc. Django provides various ready-made components such as a way to handle user authentication, a management panel for your website, forms, a way to upload files, etc.

Steps to use Tailwind CSS with Django

Step 1: Install Django package: Install the Django package via the following command.

python -m pip install Django

Step 2: Create a Django project: Create a Django project via the following command and name your Project whatever you want. Here my Project name is “myapp”.

django-admin startproject myapp

Step 3: Go inside myapp folder: We need to get inside the created folder to create other files.

cd myapp

Step 4: Create a new templates/" directory inside the project folder and update settings.py" folder.

Python




TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'], #updated part
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]


Step 5: Install Django-compressor by running the following command in your terminal.

python -m pip install django-compressor

Step 6: Add compressor to the installed apps inside the settings.py" file.

Python




INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'compressor'#updated part
]


Step 7: Configure the compressor inside the settings.py" file.

Python




COMPRESS_ROOT = BASE_DIR / 'static'
 
COMPRESS_ENABLED = True
 
STATICFILES_FINDERS = ('compressor.finders.CompressorFinder',)


Step 8: Create two new folders “static/src” and an input.css file inside those folders.
pay

Step 9: Create a new “views.py" file inside “myapp/" next to urls.py and add the following content.

Python




from django.shortcuts import render
 
def index(request):
    return render(request, 'index.html')


Step 10: Import the newly created view instance inside the urls.py" file by adding the following code.

Python




from .views import index
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index, name='index')
]


Step 11: Create a new “_base.html" file inside the templates directory and write the following code inside it. It’s a template file that serves as a base or layout for other HTML files in your application.

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</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>


Step 12: Create an “index.html" file: This will serve as the homepage.

Step 13: Now install Tailwind CSS: Run the following command on the terminal to install all the tailwind dependencies.

npm install -D tailwindcss

Step 14: Initialize the tailwind: The below command will generate a config file named “tailwind.config.js”.

npx tailwindcss init

Step 15: Configure your tailwind.config.js: To do that go inside “tailwind.config.js” and update it as given below.

Javascript




module.exports = {
      content: [
          './templates/**/*.html'
      ],
      theme: {
        extend: {},
      },
      plugins: [],
}


Step 16: Import the Tailwind CSS directives: Add the layer directives of tailwind CSS by writing the following code inside “input.css”.

CSS




@tailwind base;
@tailwind components;
@tailwind utilities;


Step 17: Compile the Tailwind CSS code: Run the following command on the terminal to compile the Tailwind CSS directives from “input.css” into CSS code in “output.css”

npx tailwindcss -i ./static/src/input.css -o ./static/src/output.css

Step 18: Check the Project Structure

idea

Step 19: Run the application: To run the application, use the command “python manage.py runserver” in the terminal.

python manage.py runserver

The above line of code will generate a localhost server & follow the server link to open the application on the web browser.

Step 20: Test Tailwind CSS with an example: Now that we have successfully set up the tailwind CSS and understand how to run the application, now, we will test with a simple example.

Example: Write the code inside “index.html”

HTML




{% extends "_base.html" %}
 
{% block content %}
      <h1 class="text-3xl text-green-800">
          GeeksforGeeks
    </h1>
      <h3 class="text-3x1 text-green-800">
          GeeksforGeeks
    </h3>
{% endblock content %}


Output:

brown



Similar Reads

What is the use of the tailwind.config.js file in Tailwind CSS ?
The tailwind.config.js file in Tailwind CSS serves as a central configuration hub for customizing the framework. It allows you to define colors, fonts, breakpoints, and more, tailoring Tailwind to fit your project's specific design and functionality requirements. Syntax:/** @type {import('tailwindcss').Config} */module.exports = { content: [], them
1 min read
How to use CSS Animations with Tailwind CSS ?
Tailwind CSS classes are used to style elements and apply animations effortlessly. Utilize Tailwind's animation utility classes to add dynamic visual effects. Combine Tailwind CSS with custom CSS animations for versatile and engaging web designs. Table of Content Tailwind CSS Animation Utility ClassesCSS Animations with Tailwind CSS and JavaScriptT
3 min read
Integrating Django with Reactjs using Django REST Framework
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django. Reactjs in a nuts
18 min read
Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
Build a Calculator with React, Tailwind, and Django
This article will guide you in creating a calculator using React and Tailwind with the Django Framework. We'll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the calculator. What is a Calculator?A calculator is a device or tool designed for performing mathematical calculations. It typ
6 min read
Build a To-Do application Using Django, React and Tailwind
This article will guide you in creating a To-Do application using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the To-Do application. What is a To-Do application?A To-Do application, also known as a task management or productivity
6 min read
Create a Counter App Using React, Tailwind and Django Framework
This article will guide you in creating a Counter using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Counter in Python using the Django Framework. What is Counter App?The Counter app is a straightforward tool designed for easy
6 min read
Storybook-tailwind. How should I add tailwind to storybook
In this article, we will guide you through the process of adding Tailwind CSS to Storybook to enhance your UI development. Storybook is an open-source UI that helps developers create reusable, organized UI components with proper documentation independently. Tailwind CSS is basically a utility-first CSS framework for building rapid custom UI. Prereq
2 min read
How to use font from local files globally in Tailwind CSS ?
Tailwind CSS provides a set of default font families that you can use in your projects. These font families are defined as utility classes in the form of font-{family-name} and can be easily applied to any HTML element. These are the default fonts that are provided by the tailwind CSS: sans: sans-serif font family, including system fonts such as Ar
4 min read
How to use template literals in Tailwind CSS to change classes dynamically ?
Tailwind CSS is a popular utility-first CSS framework used by many web developers to build modern and responsive user interfaces. It provides a wide range of pre-defined classes that can be used to style elements, but what if we want to dynamically change classes based on some condition or user input? This is where template literals come in handy.
6 min read