Forms and uploads
<Form> builds a form from a server function. Its fields, rules and labels come from the function's parameters (usually a Model), so you write each rule once:
from pyweb import App, Checkbox, Field, Form, Input, Model, Select, Submit, Textarea, server
app = App(database="sqlite:///app.db")
class Tag(Model):
name: str = Field(max=30)
class Post(Model):
title: str = Field(min=3, max=120)
body: str = ""
tags: list[Tag] = []
draft: bool = True
@server
def save_post(post: Post):
post.save()
return post
@app.page("/posts/new")
def NewPost():
<Form action={save_post} redirect="/posts/{id}">
<Input name="title" placeholder="A good title" />
<Textarea name="body" rows="8" />
<Select name="tags" />
<Checkbox name="draft" label="Keep as draft" />
<Submit>Publish</Submit>
</Form>What this compiles to
// NewPost.js
import "./forms.js";
function NewPost($s) {
const __pw_forms__ = $s["__pw_forms__"];
return [$h("form", {"method": "post", "action": $py.at($py.at(__pw_forms__, "save_post"), "url"), "enctype": $py.at($py.at(__pw_forms__, "save_post"), "enctype"), "data-pw-form": "save_post", "data-pw-rules": $py.at($py.at(__pw_forms__, "save_post"), "rules")}, () => [
$list(() => $py.at($py.at(__pw_forms__, "save_post"), "hidden"), (__pw_h) => [$h("input", {"type": "hidden", "name": $py.at(__pw_h, "name"), "value": $py.at(__pw_h, "value")})]),
$h("p", {"class": "pw-form-error", "role": "alert", "data-pw-form-error": true, "hidden": !$py.truth($py.at($py.at(__pw_forms__, "save_post"), "error"))}, () => [$t($py.text($py.at($py.at(__pw_forms__, "save_post"), "error")))]),
$h("div", {"class": "pw-field pw-input", "data-pw-field": "title"}, () => [
$h("label", {"for": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "id")}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "label")))]),
$h("input", {"id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "id"), "name": "title", "required": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "required"), "aria-invalid": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "invalid"), "aria-describedby": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "describedby"), "type": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "type"), "value": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "value"), "checked": (($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "type") === "checkbox") ? $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "checked") : null), "minlength": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "minlength"), "maxlength": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "maxlength"), "min": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "min"), "max": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "max"), "step": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "step"), "placeholder": "A good title"}),
$when(() => $py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "help")), () => [$h("p", {"class": "pw-help"}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "help")))])]),
$h("p", {"class": "pw-error", "id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "describedby"), "hidden": !$py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "error"))}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "error")))])
]),
$h("div", {"class": "pw-field pw-textarea", "data-pw-field": "body"}, () => [
$h("label", {"for": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "id")}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "label")))]),
$h("textarea", {"id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "id"), "name": "body", "required": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "required"), "aria-invalid": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "invalid"), "aria-describedby": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "describedby"), "minlength": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "minlength"), "maxlength": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "maxlength"), "rows": "8"}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "value")))]),
$when(() => $py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "help")), () => [$h("p", {"class": "pw-help"}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "help")))])]),
$h("p", {"class": "pw-error", "id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "describedby"), "hidden": !$py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "error"))}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "body"), "error")))])
]),
$h("div", {"class": "pw-field pw-select", "data-pw-field": "tags"}, () => [
$h("input", {"type": "hidden", "name": "__pw_has_tags", "value": "1"}),
$h("label", {"for": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "id")}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "label")))]),
$h("select", {"id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "id"), "name": "tags", "required": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "required"), "aria-invalid": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "invalid"), "aria-describedby": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "describedby"), "multiple": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "multiple")}, () => [$list(() => $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "options"), (__pw_o) => [$h("option", {"value": $py.at(__pw_o, "value"), "selected": $py.at(__pw_o, "selected")}, () => [$t($py.text($py.at(__pw_o, "label")))])])]),
$when(() => $py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "help")), () => [$h("p", {"class": "pw-help"}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "help")))])]),
$h("p", {"class": "pw-error", "id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "describedby"), "hidden": !$py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "error"))}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "tags"), "error")))])
]),
$h("div", {"class": "pw-field pw-checkbox", "data-pw-field": "draft"}, () => [
$h("input", {"type": "hidden", "name": "__pw_has_draft", "value": "1"}),
$h("label", null, () => [
$h("input", {"id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "id"), "name": "draft", "aria-invalid": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "invalid"), "aria-describedby": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "describedby"), "type": "checkbox", "value": "true", "checked": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "checked")}),
$t(" "),
$t("Keep as draft")
]),
$when(() => $py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "help")), () => [$h("p", {"class": "pw-help"}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "help")))])]),
$h("p", {"class": "pw-error", "id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "describedby"), "hidden": !$py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "error"))}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "error")))])
]),
$h("button", {"type": "submit", "data-pw-submit": true}, () => [$t("Publish")])
])];
}
$mount("NewPost", NewPost);page NewPost route=/posts/new
server __pw_forms__ computed per request on the server; value sent because browser code reads it
rpc POST /__pyweb/rpc/save_post (post: Post) -> Any<form method="post" data-pw-form="save_post">
<p class="pw-form-error" role="alert" data-pw-form-error></p>
<div class="pw-field pw-input" data-pw-field="title">
<label></label><input name="title" placeholder="A good title"><p class="pw-error"></p>
</div><div class="pw-field pw-textarea" data-pw-field="body">
<label></label><textarea name="body" rows="8"></textarea><p class="pw-error"></p>
</div><div class="pw-field pw-select" data-pw-field="tags">
<input type="hidden" name="__pw_has_tags" value="1"><label></label><select name="tags"></select><p class="pw-error"></p>
</div><div class="pw-field pw-checkbox" data-pw-field="draft">
<input type="hidden" name="__pw_has_draft" value="1"><label><input name="draft" type="checkbox" value="true"> Keep as draft</label><p class="pw-error"></p>
</div><button type="submit" data-pw-submit>Publish</button>
</form>What you get:
- Labels, inputs and error slots, wired up for screen readers (
label for,aria-invalid,aria-describedby). Each field is wrapped in<div class="pw-field pw-input">(orpw-textarea,pw-select, ...); errors are<p class="pw-error">. - Checks in the browser while the user types, using the Model's rules (
min,max,pattern,choices, email/url/slug formats, required), with the same messages the server uses: "Title must be at least 3 characters". - Submit without a page load. The first field with a problem gets focus; errors from the server (including your
@validateschecks and unique fields: "Email is already taken") appear next to their input.redirect="/posts/{id}"goes to that page afterwards, filling{...}from what the function returned; withoutredirect, the form is cleared and fires apw:submittedevent with the result. - It works without JavaScript. The same form is a normal
POST: on a problem the page comes back with what was typed and the messages (HTTP 422); on success the browser is redirected (303). - Safe by default. Every form carries a CSRF token (tied to a cookie and
PYWEB_AUTH_SECRET), refuses posts from other sites, and only reads the fields the action has: a browser can't setid,private=Trueorreadonly=Truefields. Each submit has a one-time key, so a double click or a retried request runs the action once and gets the same answer. - One transaction. The action runs like every server function: its writes commit together or not at all.
#Fields
| Tag | For | Notes |
|---|---|---|
<Input name="..."> | text, numbers, dates, email, url | the input type follows the field (int → number, datetime → datetime-local, Email → email) |
<Textarea name="..."> | long text | |
<Select name="..."> | choices=, Literal[...], foreign keys, many-to-many | options come from the choices or the related rows (up to 1000); many-to-many is a multiple select; or write your own <option>s inside |
<Checkbox name="..."> | bool | unticked means False |
<FileInput name="..."> | File(...) fields, UploadedFile parameters | see Uploads |
<Submit>Text</Submit> | the button | disabled while sending |
<FormError /> | messages that aren't about one field | added at the top automatically if you don't place it |
label="..." replaces the label (it defaults to the field's label= or its name: published_at → "Published at"). class= goes on the field's wrapper; other attributes (placeholder, rows, autocomplete, ...) go on the input.
#Editing a row
Pass the row as values=:
from pyweb import Checkbox, Form, Input, Submit
@app.page("/posts/{post_id}/edit")
def EditPost(post_id: int):
post = Post.get_or_404(post_id)
<Form action={save_post} values={post}>
<Input name="title" />
<Checkbox name="draft" />
<Submit>Save</Submit>
</Form>What this compiles to
// EditPost.js
import "./forms.js";
function EditPost($s) {
const __pw_forms__ = $s["__pw_forms__"];
return [$h("form", {"method": "post", "action": $py.at($py.at(__pw_forms__, "save_post"), "url"), "enctype": $py.at($py.at(__pw_forms__, "save_post"), "enctype"), "data-pw-form": "save_post", "data-pw-rules": $py.at($py.at(__pw_forms__, "save_post"), "rules")}, () => [
$list(() => $py.at($py.at(__pw_forms__, "save_post"), "hidden"), (__pw_h) => [$h("input", {"type": "hidden", "name": $py.at(__pw_h, "name"), "value": $py.at(__pw_h, "value")})]),
$h("p", {"class": "pw-form-error", "role": "alert", "data-pw-form-error": true, "hidden": !$py.truth($py.at($py.at(__pw_forms__, "save_post"), "error"))}, () => [$t($py.text($py.at($py.at(__pw_forms__, "save_post"), "error")))]),
$h("div", {"class": "pw-field pw-input", "data-pw-field": "title"}, () => [
$h("label", {"for": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "id")}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "label")))]),
$h("input", {"id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "id"), "name": "title", "required": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "required"), "aria-invalid": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "invalid"), "aria-describedby": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "describedby"), "type": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "type"), "value": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "value"), "checked": (($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "type") === "checkbox") ? $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "checked") : null), "minlength": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "minlength"), "maxlength": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "maxlength"), "min": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "min"), "max": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "max"), "step": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "step")}),
$when(() => $py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "help")), () => [$h("p", {"class": "pw-help"}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "help")))])]),
$h("p", {"class": "pw-error", "id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "describedby"), "hidden": !$py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "error"))}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "title"), "error")))])
]),
$h("div", {"class": "pw-field pw-checkbox", "data-pw-field": "draft"}, () => [
$h("input", {"type": "hidden", "name": "__pw_has_draft", "value": "1"}),
$h("label", null, () => [
$h("input", {"id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "id"), "name": "draft", "aria-invalid": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "invalid"), "aria-describedby": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "describedby"), "type": "checkbox", "value": "true", "checked": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "checked")}),
$t(" "),
$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "label")))
]),
$when(() => $py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "help")), () => [$h("p", {"class": "pw-help"}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "help")))])]),
$h("p", {"class": "pw-error", "id": $py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "describedby"), "hidden": !$py.truth($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "error"))}, () => [$t($py.text($py.at($py.at($py.at($py.at(__pw_forms__, "save_post"), "fields"), "draft"), "error")))])
]),
$h("button", {"type": "submit", "data-pw-submit": true}, () => [$t("Save")])
])];
}
$mount("EditPost", EditPost);page EditPost route=/posts/{post_id}/edit
server post computed per request; never read by browser code, never sent
server __pw_forms__ computed per request on the server; value sent because browser code reads it<form method="post" data-pw-form="save_post">
<p class="pw-form-error" role="alert" data-pw-form-error></p>
<div class="pw-field pw-input" data-pw-field="title">
<label></label><input name="title"><p class="pw-error"></p>
</div><div class="pw-field pw-checkbox" data-pw-field="draft">
<input type="hidden" name="__pw_has_draft" value="1"><label><input name="draft" type="checkbox" value="true"> </label><p class="pw-error"></p>
</div><button type="submit" data-pw-submit>Save</button>
</form>The form shows the row's values and carries its id, signed so it can't be changed in the browser. The action receives the stored row with the submitted fields applied (fields not in the form keep their values), and post.save() updates it. Still check that the current user may edit the row in your action: the signature only proves the form came from your page.
#Plain parameters
Without a Model parameter, each parameter is a field:
from typing import Literal
from pyweb.models import Email
@server
def subscribe(email: Email, plan: Literal["free", "pro"] = "free", daily: bool = False):
...Annotated[str, Field(max=40)] adds rules to a parameter. Parameters with defaults (or | None) are optional.
#Errors from your code
Raise ValidationError for problems you find yourself:
from pyweb import ValidationError
@server
def save_post(post: Post):
if Post.where(title=post.title).exists():
raise ValidationError({"title": "is already used"})
if not allowed(post):
raise ValidationError("You can't publish yet") # shown at the top of the form
post.save()Messages starting with a lowercase letter are shown after the field's label ("Title is already used").
A parameter typed date, datetime or time gets a date or time input, and the server parses and checks what arrives.
#Uploads
from pyweb.models import File
class User(Model):
avatar: str | None = File(types=["image/*"], max_size="2MB")<FileInput name="avatar" />- The file's type is read from its bytes, not its name or what the browser claims; HTML and SVG never count as images.
max_sizeis checked before saving; the whole submit is limited byPYWEB_MAX_UPLOAD(default 10MB, 413 beyond it).- Files are stored under random names; the column keeps the key.
storage.url(user.avatar)(frompyweb) gives a link. - A form with no new file keeps the old one.
- Plain parameters can take the file itself:
def upload(doc: UploadedFile)(.filename,.content_type,.size,.data,.save()), or several:def upload(photos: list[UploadedFile])makes the inputmultipleand gives a list (empty when nothing was chosen).
With JavaScript, files can be dropped on the field, the chosen ones are listed under it (a preview for images, a Remove button each), and a bar shows how much of the upload has been sent. Dropped files that don't match accept= are left out.
Where files go is set by PYWEB_STORAGE:
| Value | Storage |
|---|---|
file://./uploads (default) | a folder on the server; served from /__pyweb/files/... with nosniff, a sandboxing CSP, and Content-Disposition: attachment for anything that isn't media, PDF or text |
s3://bucket/prefix | S3 or any S3-compatible store (S3_ENDPOINT for R2, MinIO, Spaces); signed with AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_REGION, no SDK needed |
With S3, storage.storage().upload_url(filename) returns a key and a presigned URL, so large files can go from the browser straight to the bucket.
#Multi-step forms
In one page, the UI kit's Stepper shows one step at a time and checks a step's fields before moving on:
from pyweb.ui import Stepper, Step
<Form action={sign_up}>
<Stepper submit="Create account">
<Step title="Account">
<Input name="email" />
</Step>
<Step title="Profile">
<Input name="name" />
</Step>
</Stepper>
</Form>The whole form is still one submit, checked again on the server; an error on an earlier step's field takes you back to it. Across pages, carry earlier steps' answers in a signed hidden value:
from pyweb import forms
token = forms.carry({"email": email, "plan": plan}) # put in a hidden input on the next step
data = forms.restore(token) # None if changed or older than an hour#Without <Form>
Every server function also has a JSON endpoint (see Server functions), and Models validate on save(), so you can build any form by hand with bind= and an onclick handler.