Skip to content

Instantly share code, notes, and snippets.

@bpeterso2000
Created April 25, 2025 14:57
Show Gist options
  • Save bpeterso2000/ec0e8ef8c68bbbb5d328735ae1ad01b2 to your computer and use it in GitHub Desktop.
Save bpeterso2000/ec0e8ef8c68bbbb5d328735ae1ad01b2 to your computer and use it in GitHub Desktop.
from fasthtml.common import *
from fastlite import *
from dataclasses import dataclass
from typing import Optional
# Initialize FastHTML app with PicoCSS and SQLite database
db = database('data/users.db')
app, rt = fast_app(pico=True)
# Define User dataclass for form data
@dataclass
class User:
name: str
email: str
id: Optional[int] = None
# Create users table
users = db.create(User, pk='id')
# Form generator with error handling
def mk_form(user=None, errors=None):
errors = errors or {}
return Form(
Group(
Div(
Label("Name", _for="name"),
Input(
id="name",
name="name",
value=user.name if user else "",
required=True,
minlength=2,
placeholder="Enter your name"
),
Small(errors.get("name", ""), style="color: red") if errors.get("name") else None
),
Div(
Label("Email", _for="email"),
Input(
id="email",
name="email",
type="email",
value=user.email if user else "",
required=True,
placeholder="Enter your email"
),
Small(errors.get("email", ""), style="color: red") if errors.get("email") else None
),
Button("Submit")
),
hx_post="/submit",
hx_target="#result"
)
# Home route with form
@rt("/")
def get():
return Titled(
"User Registration",
mk_form(),
Div(id="result"),
# List of submitted users
Ul(*[Li(f"Name: {u.name}, Email: {u.email}") for u in users()])
)
# Form submission handler with validation
@rt("/submit")
async def post(user: User):
errors = {}
# Server-side validation
if not user.name or len(user.name) < 2:
errors["name"] = "Name must be at least 2 characters long"
if not user.email or "@" not in user.email:
errors["email"] = "Please enter a valid email address"
# If errors, return form with error messages
if errors:
return mk_form(user, errors)
# Insert valid data into database
users.insert(user)
# Return success message and clear form
return Div(
P("Registration successful!"),
mk_form(),
hx_swap="outerHTML"
)
# Start the server
serve()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment