A powerful, modern web application template that combines Django's robust backend with SvelteKit's reactive frontend. This template provides everything you need to build full-stack web applications with best practices and modern tooling.
Note: This template uses Svelte 5 with Runes [Strict]
-
Clone the Repository
git clone git@github.com:Bishwas-py/django-svelte-template.git cd django-svelte-template -
Initialize Development Environment
# First, initialize development tools and commands source bin/setup # Then, configure your development environment configure
This two-step process will:
- Make development commands available (
source bin/setup) - Check and install required dependencies (
configure) - Create a Python virtual environment
- Set up configuration files (db.py, env.py, mail.py)
- Install frontend dependencies
- Set up pre-commit hooks for code quality
- Make development commands available (
-
Start Development Servers
run # Starts all development serversThis will start:
- Django backend at
http://localhost:8000 - SvelteKit frontend at
http://localhost:5173 - Test email server at
localhost:1725
- Django backend at
-
Format Code (Optional)
format # Runs pre-commit hooks to format and lint all files
β¨ After setup, you'll see a feature-rich todo app demonstrating the template's capabilities. Feel free to remove it and start building your own application.
-
bin/setup: Development environment initialization that:- Makes development commands available in your shell
- Must be sourced first:
source bin/setup - Provides access to
configure,run, andformatcommands
-
configure: Project configuration command that:- Sets up Python virtual environment
- Installs project dependencies
- Creates configuration files
- Sets up pre-commit hooks
- Only available after running
source bin/setup
-
run: Unified development server management- Starts all development servers
- Available after running
source bin/setup
- Django: Production-ready web framework with powerful ORM and admin interface
- Djapy: Django-Pydantic integration for robust API validation
- Pydantic: Data validation using Python type annotations
- Custom Request Handler: Seamless SvelteKit-Django request handling via
callViaRouteName
- SvelteKit: Next-generation frontend framework with Svelte 5
- Tailwind CSS: Utility-first CSS framework for rapid UI development, proudly Tailwind 4
- TypeScript: Enhanced type safety and developer experience
- β Automated development environment setup
- β Type-safe API interactions
- β Built-in form validation
- β Toast notifications system
- β Flash messages support
- β Dark mode Swagger UI
- β Modern, responsive UI components
- β Code formatting and linting with pre-commit hooks
The template uses a standard SvelteKit layout structure with TypeScript integration. The base layout file (src/+layout.svelte) sets up core functionality:
<script>
import "../app.css";
import PutFlash from "$items/PutFlash.svelte";
import Flash from "$items/Flash.svelte";
let {children} = $props();
</script>
<PutFlash/>
<Flash/>
{@render children()}Server-side flash messages are handled by the PutFlash and Flash components (src/items/):
{
"message": "Error message", // Required: Message content
"message_type": "error", // Required: error, success, info, warning
"alias": "error", // Optional: For message grouping
"action": { // Optional: Call-to-action button
"path": "/login",
"label": "Login here"
}
}Use the notifier store for client-side toast notifications:
import { addToast, dismissToastAfter } from "$lib/stores/notifier.svelte";
// Persistent toast
addToast({
message: 'Hello World',
message_type: 'success'
});
// Auto-dismissing toast
dismissToastAfter(
addToast({
message: 'Hello World',
message_type: 'success'
})
);Example component usage:
<script>
import { addToast, dismissToastAfter } from "$lib/stores/notifier.svelte";
</script>
<button
onclick={() => {
dismissToastAfter(
addToast({
message: 'Hello World',
message_type: 'success'
})
)
}}
>
Show Notification
</button>User and site data are loaded through SvelteKit's server-side load functions:
// src/+layout.server.ts
import type { LayoutServerLoad } from "./$types";
export const load: LayoutServerLoad = async (event) => {
return {
current_user: event.locals.current_user,
site_data: event.locals.site_data
};
};This data is populated by the server middleware in hooks.server.ts.
The template provides robust form handling through two main components:
-
Form Component (
src/items/Form.svelte)- Loading state management
- Enhanced form actions
- Post-submit callbacks
- Automatic error handling
-
Error Component (
src/items/Error.svelte)- Seamless Pydantic validation integration
- User-friendly error display
- Automatic error filtering and formatting
2024-06-11_10-56-03.mp4
<script lang="ts">
import Error from "$items/Error.svelte";
</script>
<input type="text" name="username"/>
<Error for="username" {uniq}/>The uniq prop is provided by the parent Form component to associate errors with specific fields.
This template includes a custom request handling system that seamlessly connects SvelteKit forms with Django URL patterns using Django's URL names.
<!-- src/routes/+page.svelte -->
<Form action="?/create_todo" method="post">
<!-- Form fields -->
</Form>Register form actions in src/routes/+page.server.ts using our custom callViaRouteName function:
import { callViaRouteName } from "$lib/server/repl";
// Single action - matches Django URL name 'create_todo'
export const actions = callViaRouteName('create_todo');
// Multiple actions with specific HTTP methods
export const actions = callViaRouteName([
{ name: 'create_todo', method: 'POST' }, // Matches Django URL name
{ name: 'delete_todo', method: 'DELETE' } // Matches Django URL name
]);<Form action="?/call&s=/todos/update/{todo.id}/&m=post">
<!-- Form fields -->
</Form>// src/routes/+page.server.ts
import { flashRedirect } from "$lib/server/flash";
export const load: PageServerLoad = async (event) => {
if (!event.locals.current_user) {
flashRedirect(event.cookies, {
message: 'Login required',
message_type: 'error',
alias: 'auth_error' // Alias is required for flash messages
}, 302, '/login');
}
return { todos: await get_todos(event) };
}Use the $api alias for backend requests:
event.fetch(`$api/endpoint`, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' }
});The authentication app (django_backend/authentication/) provides:
- Session-based authentication
- Email verification
- Password reset
- User management
Key components:
auth_views.py: Core authenticationconfirm_email_views.py: Email verificationforgot_password_views.py: Password recoveryusers_views.py: User management
- Each Django app contains:
schema.py: Pydantic modelsviews.py: API endpointsurls.py: URL routing
The home app provides:
- Initial data loading
- User session management
- CSRF protection
- Site configuration
The development environment is initialized in two steps:
-
Source Setup Script
source bin/setupThis makes development commands available in your shell.
-
Run Configuration
configure # This command is available after running source bin/setupThis sets up your development environment with all necessary dependencies and tools.
Note: The
configurecommand becomes available only after runningsource bin/setup
After completing the setup, you'll have access to:
-
runCommandrun # Starts all development servers- Django backend:
http://localhost:8000 - SvelteKit frontend:
http://localhost:5173 - Email server:
localhost:1725
- Django backend:
-
Code Quality Tools
format # Run all formatters and lintersThe template includes comprehensive code quality tools enforced via pre-commit hooks:
Python (Django Backend)
- Black code formatter
- isort import sorting (Black profile)
- Flake8 linting with bugbear plugin
Frontend (SvelteKit)
- Prettier formatting
- Svelte component checking
- ESLint with TypeScript
General
- YAML validation
- File formatting (trailing whitespace, EOF fixing)
- Large file checks
- Commitizen for consistent commit messages
The development servers can be started from any project directory, and hot-reloading is enabled for both frontend and backend changes.