Django with Tailwind CSS
Reference:
https://www.djangoproject.com/
https://tailwindcss.com/
prerequisite: python and nodejs installed
Step 1: Preparation, Create Django Project, Inital Migration
create virtualenv: virtualenv venv
start virtualenv: venv/Scripts/activate
install Django in virtualenv: pip install django==4.2
Create Django: django-admin startproject myproject
Go to myproject folder: cd myproject
Initial Migration: python manage.py migrate
Add static folder: mkdir static
Add template folder: mkdir templates
Step 2: Create Django Apps
Create apps: python manage.py startapp myapp
Step 3: Project Setting: Register Apps, Set Templates Folder (myproject/settings.py)
...
INSTALLED_APPS = [
...
'myapp', #updated
]
...
TEMPLATES = [
...
'DIRS': [Path(BASE_DIR, 'templates')], #updated
...
]
...
STATICFILES_DIRS= [Path(BASE_DIR,'static'),] #updated
...
Step 4: Add Tailwind CSS : Install, Initialization
Install: npm install -D tailwindcss
Initialization: npx tailwindcss
Update tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./templates/**/*.html' //updated
],
theme: {
extend: {},
},
plugins: [],
}
Step 5: Add Directive, Build
Create /static/css/input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Build: npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css -w
Step 6: Create HTML Files
Create templates/index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django Tailwind</title>
<link rel="stylesheet" href="{% static 'css/output.css' %}">
</head>
<body>
<main class="container mx-auto px-4">
<h1 class="text-3xl text-red-800">
Hello World!
</h1>
<h3 class="text-red-800">
This is django with tailwind css
</h3>
</main>
</body>
</html>
Step 7: Create Function Views myapp/views.py
from django.shortcuts import render
from .models import Movie
# Create your views here.
def index(request):
template = 'index.html'
extra_context = {}
return render(request, template, extra_context)
Step 8: Setup URLS
Create myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
Update myproject/urls.py
from django.contrib import admin
from django.urls import path, include #updated
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), #updated
]
Step 9: Run Server and Testing
Run Server: python manage.py runserver
Access: http://127.0.0.1:8000
Project Structure: