Integrate SurveyJS with Django
SurveyJS libraries enable you to display and edit web forms, collect answers, analyze results, and generate PDF forms in the browser. Your backend supplies the data these libraries need and stores the changes they produce. The libraries exchange JSON with your backend, which allows you to use any database and storage services.
This guide explains how to integrate SurveyJS with your Django backend. It walks through all backend-specific workflows, starting with the minimum integration: saving a completed response. Each workflow description provides client and server code samples and a link to a live example.
Run Forms
SurveyJS Form Library displays a form using a JSON schema and collects the respondent's answers. Start integration by adding an endpoint that saves those answers. You can then load data from the server, save progress in unfinished forms, and add the other features described below if your application needs them.
Save Responses
To collect responses, your backend needs an endpoint that accepts and stores answers. The form JSON schema can be a JavaScript constant on the page for now—this first step does not require an endpoint for loading it.
When the respondent completes the form, SurveyJS raises the onComplete event. Handle it to send survey.data and the form ID to your save endpoint. The backend should store the answers as a single JSON document and return the saved response's ID to confirm that the save succeeded.
Store the response exactly as it arrives—spaces, empty strings, and empty objects may be meaningful.
Client code
// Define the form directly in the page - no database needed
const definition = {
title: "Contact us", completeText: "Send message",
elements: [
{ type: "text", name: "email", title: "Your email", inputType: "email", isRequired: true },
{ type: "comment", name: "message", title: "How can we help?", isRequired: true }
]
};
const survey = new Model(definition);
// Save after completion; SurveyJS offers a retry action if saving fails
survey.onComplete.add(async (sender, options) => {
try {
const response = await fetch("/api/responses", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ formId: "contact", data: sender.data })
});
const { id } = response.ok ? await response.json() : {};
if (!Number.isInteger(id) || id < 1) throw new Error("Missing response ID");
sender.setVariable("responseId", id);
options.showSaveSuccess();
} catch {
options.showSaveError("We couldn't save your message. Please try again.");
}
});
Server code
# POST /api/responses: Store submitted answers as one JSON document
def save(request: HttpRequest) -> JsonResponse:
# The raw body, not request.POST or a serializer: json.loads keeps every key and value as it was sent
body = read_json(request)
if not isinstance(body, dict) or "formId" not in body or "data" not in body:
return JsonResponse({"error": "Expected { formId, data }"}, status=400)
id = insert_response(body["formId"], body["data"]) # stored as it arrived: {} stays {}, 1.0 stays 1.0
return JsonResponse({"id": id}, status=201)
Load JSON Schemas, Variables, and Answers
As your application grows, the same form may need to dynamically change, behave differently for different users, or open with answers already filled in. Your backend can provide the JSON schema, variables, and previous answers needed to prepare the form.
JSON schema
Form JSON schema describes the questions, layout, and logic. You can include the schema in the page when the latter renders or fetch it from an endpoint before displaying the form. In either case, the server can dynamically adjust the schema for the current request.Variables
Variables provide context for the form. For example, the current user's name can appear in a title, and their subscription plan can control which questions are visible. Variables are excluded from the saved answers.Previous answers
If the user is returning to an existing record, also load its answers and assign them tosurvey.data. The form then opens with those values already filled in.
An endpoint can return all three pieces of data in one request.
Client code
import { Model } from "survey-core";
async function createSurvey(recordId) {
if (window.FORM_DEFINITION) {
// Option A: Use the schema and user variables embedded in the HTML response
const survey = new Model(window.FORM_DEFINITION);
survey.setVariables(window.FORM_VARIABLES);
return survey;
}
// Option B: Load the definition, variables, and previous answers in one request
const { definition, variables, data } =
await fetch(`/api/forms/claim-request?record=${encodeURIComponent(recordId)}`).then(r => r.json());
const survey = new Model(definition);
survey.setVariables(variables); // Variables are available in expressions such as {user.name} and are excluded from survey.data
survey.data = data; // Restore previously saved answers for editing
return survey;
}
Server code
# Option A: Embed the schema and user variables in the HTML response
def claim_page(request: HttpRequest) -> HttpResponse:
definition = json.loads(DEFINITION.read_text(encoding="utf-8"))
user = request.user
variables = {"user": {"name": user.get_full_name(), "plan": user.plan} if user.is_authenticated else {"name": None, "plan": None}}
# The template writes both with json_script, which escapes them for the page
return render_example(request, "load-definition-variables-data", form_definition=definition, form_variables=variables)
# Option B: Return the definition, variables, and previous answers in one response
def get_form(request: HttpRequest, form_id: str) -> JsonResponse:
if (form := Form.objects.filter(key=form_id).first()) is None:
return JsonResponse({"error": "Unknown form"}, status=404)
user, record = request.user, request.GET.get("record", "")
saved = Response.objects.filter(id=record) if record.isdigit() else Response.objects.none()
if form_id == "claim-request": # only the signed-in customer's own claims
email = user.email if user.is_authenticated else ""
saved = saved.annotate(email=JsonExtract("data", "$.customer_email")).filter(form_id="claim", email=email)
answers = saved.values_list("data", flat=True).first()
return JsonResponse({
"definition": json.loads(form.json), # the stored form definition
"variables": {"user": {"name": user.get_full_name(), "plan": user.plan} if user.is_authenticated else {"name": None, "plan": None}},
"data": json.loads(answers) if answers else {}, # previous answers, or {} without them
})
Live Example: Load JSON Schemas, Variables, and Answers
Resume Progress
With long forms, respondents may need to stop and return later. You can save their answers together with the form's UI state, which includes the current page and focused input field. Restoring both lets them continue from the same place.
While the respondent works, listen for answer and page changes and send the updated progress to the backend. Answer changes can happen on every keystroke, so wait for a short pause before saving. Send any pending changes when users close or reload the browser tab as well.
The backend should store one progress document for each user and form. When the respondent returns, load that document and restore the answers and UI state before they continue.
Client code
import debounce from "lodash/debounce";
const saveProgress = debounce(() => flushProgress().catch(showSaveError), 800);
function flushProgress() {
saveProgress.cancel();
if (pendingProgress === null) return saving ?? Promise.resolve();
return saving ??= persistProgress().finally(() => { saving = null; });
}
function queueProgress() {
if (!recording || locked) return;
const body = JSON.stringify(snapshot());
if (body === lastSnapshot) return;
lastSnapshot = pendingProgress = body;
setStatus("Changes will be saved automatically");
saveProgress();
}
survey.onValueChanged.add(queueProgress);
survey.onUIStateChanged.add(queueProgress); // Include page and focus changes
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden" && recording && !locked) {
flushProgress().catch(showSaveError);
}
});
Server code
# Return the current user's saved answers and UI state, or null when there is no draft
def load_progress(request: HttpRequest, form_id: str) -> HttpResponse:
if not request.user.is_authenticated:
return JsonResponse({"error": "Sign in to load progress"}, status=401)
draft = Progress.objects.filter(key=f"{request.user.pk}:{form_id}").values_list("json", flat=True).first()
return HttpResponse(draft or "null", content_type="application/json") # as stored
# Store progress under a key containing both the user ID and form ID
def save_progress(request: HttpRequest, form_id: str) -> HttpResponse:
if not request.user.is_authenticated:
return JsonResponse({"error": "Sign in to save progress"}, status=401)
# The raw body, not request.POST: { data, uiState } is stored as it arrived, {} stays {}
Progress.objects.update_or_create(key=f"{request.user.pk}:{form_id}", defaults={"json": dumps(read_json(request))})
return HttpResponse(status=204)
Store Files Separately
A File Upload question can store file contents in the response as Base64 strings. This makes responses much larger. Alternatively, you can keep files in a separate storage. To do this, set the question's storeDataAsText property to false and handle the survey's onUploadFiles event.
The event handler should send selected files to an upload endpoint. The backend stores each file and returns its ID or URL. The form saves that reference in the answers, leaving the file contents out of the response document.
For private files, use IDs and a download endpoint that checks the user's access before returning a file. Handle the onDownloadFile event to retrieve the content when the form needs to display a preview.
Client code
// Upload: your server stores the files and returns an id (or a URL) for each
survey.onUploadFiles.add(async (_, options) => {
const body = new FormData();
options.files.forEach(file => body.append("files[]", file)); // "files[]": PHP keeps only the last of several "files"
const response = await fetch("/api/files", { method: "POST", body }).catch(() => null);
const ids = response?.ok ? await response.json().catch(() => null) : null;
if (!Array.isArray(ids) || ids.length !== options.files.length || ids.some(id => typeof id !== "string" || !id)) {
return options.callback([], ["Couldn't upload files. Please try again."]);
}
// The response stores these ids, not the file contents
options.callback(options.files.map((file, i) => ({ file, content: ids[i] })));
});
Server code
# POST /api/files — store uploads, return their ids in the same order
def upload(request: HttpRequest) -> JsonResponse:
# Field "files[]", the name on every platform. Not request.FILES["files[]"]: that is only the last file
files = request.FILES.getlist("files[]")
if not files:
return JsonResponse({"error": 'Upload one or more files in a field named "files[]"'}, status=422)
types = [detect_type(file.read(4096)) for file in files] # by the bytes, never the client's type
for file, type in zip(files, types): # check the whole batch before storing any
if file.size > MAX_BYTES:
return JsonResponse({"error": "Each file must be 5 MB or less"}, status=422)
if type not in TYPES:
return JsonResponse({"error": f"{file.name} is not a PNG, JPEG, WebP, GIF or PDF file"}, status=422)
storage, ids = uploads(request), []
for file, type in zip(files, types):
id = str(uuid.uuid4())
storage.save(id, file) # named by id, never by the client
File.objects.create(id=id, name=file.name, type=type)
ids.append(id)
return JsonResponse(ids, safe=False)
Live Example: Store Files Separately
Load Choices from Web
Choice lists often come from data your application already stores, such as products or offices. Use the choicesByUrl property to load those options into a Dropdown, Checkboxes, or Radio Button Group question. The configured endpoint should return the list, and SurveyJS displays it as the question's choices.
The URL can include answers or variables in curly braces. For example, /api/offices?region={region} uses the selected region to request matching offices. When that answer changes, SurveyJS requests the list again.
The browser calls the URL directly. If an external service needs a secret key or does not allow cross-origin requests, have your backend call it and return the choices to the browser. If your own endpoint requires authentication headers, add them through settings.web.onBeforeRequestChoices.
Client code
// Use choicesByUrl in the form definition to load lists from API endpoints
// "choicesByUrl": { "url": "/api/offices?region={region}", "valueName": "id", "titleName": "name" }
// "choicesByUrl": { "url": "/api/countries", "valueName": "code", "titleName": "name" }
// SurveyJS replaces {region} with the selected region and reloads the office list when the region changes
// Optional: add your auth header to every choices request
import { settings } from "survey-core";
settings.web.onBeforeRequestChoices = (_, options) => {
options.request?.setRequestHeader("Authorization", `Bearer ${token}`);
};
Server code
# GET /api/offices?region= — {region} from the form arrives as a query parameter
def offices(request: HttpRequest) -> JsonResponse:
region = request.GET.get("region", "")
return JsonResponse(list(Office.objects.filter(region=region).order_by("name").values("id", "name")), safe=False)
# GET /api/countries — a proxy: the browser can't call a service without CORS, your server can
async def countries(request: HttpRequest) -> JsonResponse:
countries = await cache.aget("countries")
if countries is None:
try:
answer = await http.client().get("https://restcountries.com/v3.1/all", params={"fields": "name,cca2"}, timeout=5)
countries = sorted(({"code": c["cca2"], "name": c["name"]["common"]} for c in answer.raise_for_status().json()),
key=lambda country: country["name"])
await cache.aset("countries", countries, DAY)
except Exception as error: # down, or a different answer: the bundled list for 10 minutes, not a timeout each
log.warning("restcountries.com failed (%s); serving shared/seed/countries.json", error)
countries = json.loads(BUNDLED_COUNTRIES.read_text(encoding="utf-8"))
await cache.aset("countries", countries, 10 * 60)
return JsonResponse(countries, safe=False, headers={"Cache-Control": "public, max-age=86400"})
Live Example: Load Choices from Web
Async Calculations and Validation
Some form logic needs information that only your backend has. For example, a validation rule may need to check whether an email address is already registered, or a calculation may need the shipping rate for a postcode.
Register an expression function with isAsync: true and have it request that information from your backend. The function returns a promise. When the request finishes, SurveyJS uses the result to update the calculation, validation rule, or visibility condition that called the function.
Client code
// Validate email availability using the backend's customer records
registerFunction({
name: "emailExists",
isAsync: true,
func: async ([email]) => {
const key = normalize("email", email);
if (!key) return false;
return lookup("email", key, `/api/customers/exists?email=${encodeURIComponent(key)}`, "exists");
}
});
// Share one shipping lookup between the calculation and the postcode validator
registerFunction({
name: "shippingCost",
isAsync: true,
func: async ([postcode]) => {
const key = normalize("postcode", postcode);
if (!key) return null;
return lookup("postcode", key, `/api/shipping?postcode=${encodeURIComponent(key)}`, "price");
}
});
Server code
# GET /api/customers/exists?email= — answers emailExists()
def customer_exists(request: HttpRequest) -> JsonResponse:
email = request.GET.get("email", "").strip().lower()
return JsonResponse({"exists": Customer.objects.filter(email=email).exists()})
# GET /api/shipping?postcode= — answers shippingCost(): the longest matching postcode prefix wins,
# { "price": null } when none matches (the form shows "We don't deliver to this postcode yet")
def shipping(request: HttpRequest) -> JsonResponse:
postcode = request.GET.get("postcode", "").replace(" ", "").upper()
if not POSTCODE.match(postcode):
return JsonResponse({"price": None})
prefixes = [postcode[:length] for length in range(1, len(postcode) + 1)]
rate = ShippingRate.objects.filter(postcode_prefix__in=prefixes).order_by(Length("postcode_prefix").desc()).first()
return JsonResponse({"price": float(rate.price) if rate else None}) # a DecimalField: send it as a number
Live Example: Async Calculations and Validation
Use Relational Storage
Storing each response as JSON is enough to preserve its answers. If you also need to query those answers with SQL or join them with other application data, copy the relevant values into database columns.
First, give the answers stable keys. A question's valueName sets the key it writes into the response independently of its question name. Form authors can then rename or move questions without breaking the mapping to your columns. If you need more mapping information, add a custom question property and expose it in Survey Creator's Property Grid.
When saving, keep the original JSON and the version of the form JSON schema used to collect it. Then copy the mapped values into their columns. Save both in one transaction, so the records stay consistent. Keeping the original document and schema version also lets you rebuild the mapping if your tables change later.
Client code
import { Model, Serializer } from "survey-core";
// Optional metadata describing the columns used by the server
Serializer.addProperty("question", { name: "dbColumn", category: "data" });
// Keep answer keys stable when question names change
const survey = new Model(definitions[definitionVersion]);
survey.completeText = "Submit claim";
Server code
# POST /api/claims — original JSON first, then the columns you query
def save_claim(request: HttpRequest) -> JsonResponse:
# The raw body, not request.POST: the stored answers keep every key, {} and 1.0 as they arrived
body = read_json(request)
if not isinstance(body, dict) or body.get("data") is None or body.get("definitionVersion") is None:
return JsonResponse({"error": "Expected { data, definitionVersion }"}, status=400)
data = body["data"]
answers = data if isinstance(data, dict) else {}
with transaction.atomic(using=router.db_for_write(Claim)): # both rows or neither, in the router's database
id = insert_response("claim", data, body["definitionVersion"]) # the original and its version
Claim.objects.create(response_id=id, customer_email=answers.get("customer_email"), # keys come from valueName
amount=answers.get("amount"))
return JsonResponse({"id": id}, status=201)
Live Example: Use Relational Storage
Fill Forms Together
Several people may need to fill out the same record, such as a dispatcher and a technician completing a job sheet. Participants see each other's answers, focus, and cursors.
To let participants fill out a form together, follow these steps:
- Add
CollaborationPluginfromsurvey-core/collaborationto enable this functionality. - Connect the clients to a WebSocket relay that groups participants by record. When someone joins, the relay sends the form JSON schema and current answers so that their form starts in the same state as everyone else's.
- Have the relay keep the latest value for each question and forward changes to the other clients. If two people change the same question, the last change wins.
- Save the completed response through the usual save endpoint.
Client code
// Transport the plugin's answer and presence messages over a WebSocket
function applySharedState(message) {
const draft = survey?.data;
const previousSession = sessionId;
if (!collab) {
survey = new Model(message.seed);
survey.completeText = "Finish job sheet";
collab = new CollaborationPlugin(survey, { getInviteLink: partnerLink });
collab.onEvent.add((_, { message }) => {
if (ready && responseId === null && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
});
survey.onComplete.add(completeJobSheet);
mountSurvey(survey);
}
sessionId = message.sessionId;
ready = true;
collab.apply(message);
// Restore the local draft if an empty session replaces the disconnected one
if (previousSession && previousSession !== sessionId && !message.responseId && !message.peers.length) survey.data = draft;
form.hidden = false;
document.getElementById("collaboration-loading").hidden = true;
setLocked(false);
if (message.responseId) confirmCompletion(message.responseId, message.values);
}
Server code
# The relay runs in this app's process, on its port, and relays JSON: it never parses the definition
async def connect(self):
record_id, user = self.scope["url_route"]["kwargs"]["record_id"], self.scope["user"]
key = room_key.for_scope(self.scope, record_id)
if not user.is_authenticated or not RECORD_ID.match(record_id) or key is None: # stands in for your session check
await self.close() # before accept(): the browser sees a refused handshake
return
await self.accept()
self.room = await fill_room.join(key, lambda: database_sync_to_async(seed)(record_id)) # definition + answers
self.participant = self.room.add(display_name(self.scope, user.get_full_name()))
await self.channel_layer.group_add(self.room.group, self.channel_name)
await self.send(text_data=dumps({
"type": "init", "clientId": self.participant.id, "name": self.participant.name,
"colorIndex": self.room.color_index(self.participant), "seed": self.room.seed, "values": self.room.values,
"peers": self.room.roster(self.participant), "sessionId": self.room.session_id,
"responseId": self.room.response_id,
})) # init first
async def receive(self, text_data=None, bytes_data=None):
message = parse(text_data) # objects stay objects: {} is relayed as {}
if not isinstance(message, dict):
return
kind = message.get("type")
if kind == "complete" and isinstance(message.get("data"), dict):
await self.complete(message["data"])
elif kind == "value" and isinstance(message.get("key"), str) and self.room.response_id is None:
self.room.values[message["key"]] = message.get("value") # last write wins
await self.broadcast({"type": "value", "from": self.participant.id, "key": message["key"],
"value": message.get("value")})
elif kind == "presence" and message.get("state") is not None and len(text_data) <= 4096:
retain = message.get("retain") is not False # stamp identity, relay
if retain:
self.participant.state = message["state"]
await self.broadcast({"type": "peer", "retain": retain, "peer": self.room.peer(self.participant, message["state"])})
# unknown types: ignore
async def disconnect(self, code):
if hasattr(self, "participant"): # peer-left to the others; the room is dropped 2 s after the last leaves
fill_room.leave(self.room, self.participant)
await self.broadcast({"type": "peer-left", "clientId": self.participant.id})
await self.channel_layer.group_discard(self.room.group, self.channel_name)
Live Example: Fill Forms Together
Analyze Results with Dashboard
Once you have collected responses, use SurveyJS Dashboard to display and analyze them. Dashboard runs in the browser and uses the form JSON schema to choose a chart for each question automatically.
Load the JSON schema and request the saved responses for that form. The backend should return the answers as a JSON array, which the client passes to Dashboard along with the schema.
As the number of responses grows, you can filter or paginate them on the server. This lets users load the data they need without sending every stored response to the browser.
Client code
// Load answers with their submission dates for Dashboard's built-in date filter
async function loadResults(signal) {
const query = new URLSearchParams({ formId: "feedback", includeCreatedAt: "1", limit: "5000" });
const [definition, response] = await Promise.all([
loadSchema(), fetch(`/api/responses?${query}`, { signal })
]);
if (!response.ok) throw new Error("Responses load failed");
const data = await response.json();
if (!Array.isArray(data)) throw new Error("Invalid responses");
return { definition, data: data.map(row => ({ ...row.data, createdAt: row.createdAt })) };
}
function renderResults(definition, data) {
if (!dashboard) {
const survey = new Model(definition);
dashboard = new Dashboard({
questions: survey.getAllQuestions(), data,
dateFieldName: "createdAt", datePeriod: "last30days"
});
dashboard.render(container);
} else {
dashboard.updateData(data);
}
}
Server code
# GET /api/responses?formId=&includeCreatedAt=&from=&to=&limit=&offset=
def responses(request: HttpRequest) -> HttpResponse:
query = request.GET
try: # page on the server for large volumes
limit, offset = min(max(int(query.get("limit", 500)), 1), 5000), max(int(query.get("offset", 0)), 0)
except ValueError:
return JsonResponse({"error": "limit and offset must be whole numbers"}, status=400)
rows = Response.objects.filter(form_id=query.get("formId", ""), created_at__gte=query.get("from", ""))
if to := query.get("to"): # ISO 8601 UTC strings compare as dates; `to` includes that whole day
rows = rows.annotate(day=Substr("created_at", 1, 10)).filter(day__lte=to)
rows = rows.order_by("created_at", "id").values_list("data", "created_at")[offset:offset + limit]
# Include submission dates separately when requested by Dashboard
if query.get("includeCreatedAt") in ("1", "true"):
return JsonResponse([{"data": json.loads(data), "createdAt": created_at} for data, created_at in rows], safe=False)
return HttpResponse("[" + ",".join(data for data, _ in rows) + "]", content_type="application/json") # as stored
Live Example: Analyze Results with Dashboard
Edit Forms in Survey Creator
Survey Creator lets authors build and edit forms in your application. It works with the same form JSON schemas that Form Library displays to respondents. Your backend should load those schemas when the editor opens and save them when an author makes changes.
Load and Save Form JSON Schemas
Start by loading the saved schema into Survey Creator. You can use the same endpoint that supplies the schema to Form Library.
When the author clicks Save, Survey Creator calls saveSurveyFunc. Use this function to send the updated JSON schema to your backend. The backend should check the author's permission to edit forms, store the JSON, and confirm that it was saved. The next time a respondent opens the form, Form Library loads the updated JSON schema.
To save after each change, set the autoSaveEnabled property to true. Survey Creator then calls the same save function automatically. If the backend rejects a save, the backend should report the failure to Survey Creator so that the author can see it.
Client code
const creator = new SurveyCreator({ showTranslationTab: true });
// Queue writes so an older request cannot overwrite newer edits
const saver = createSchemaSaver(() => creator.JSON, async json => {
const response = await fetch(`/api/forms/${formId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: json
});
if ([401, 403].includes(response.status)) saveDenied = true;
if (!response.ok) throw await responseError(response, "Couldn't save the form schema. Please try again.");
}, updateSaveState);
creator.saveSurveyFunc = (saveNo, callback) => {
saver.save().then(saved => {
callback(saveNo, saved);
// Creator says "not saved" in the callback; show the server's reason after it
if (!saved) creator.notify(saver.error, "error");
});
};
Server code
# PUT /api/forms/<id> — store the definition as-is: it's one JSON document
def put_form(request: HttpRequest, form_id: str) -> HttpResponse:
if not can(request.user, "edit-forms"): # editing is an admin action: 403 otherwise
return JsonResponse({"error": "You don't have editor rights: only editors can change forms"}, status=403)
# The raw body, not request.POST or a serializer: a serializer would drop the keys it doesn't declare
Form.objects.update_or_create(key=form_id, defaults={"json": dumps(read_json(request))}) # {} stays {}, 1.0 stays 1.0
return HttpResponse(status=204) # the next page load renders the new version
Live Example: Load and Save Form JSON Schemas
Upload Files
Authors may need to add a logo, image, or file to a form. You can keep these files in your storage and save their URLs in the JSON schema to keep it small.
When an author selects a file, Survey Creator raises the onUploadFile event. Handle it by sending the file to your upload endpoint, then pass the returned URL back to Survey Creator. Survey Creator adds the URL to the JSON schema, and the next save preserves that reference.
You can reuse the storage endpoint for respondent uploads. If the file is private, its URL should point to a download endpoint that checks access before serving the file.
Client code
// Store each uploaded image separately and keep its URL in the form schema
creator.onUploadFile.add(async (_, options) => {
const label = options.propertyName === "logo" || options.elementType === "header" ? "Logo" : "Image";
uploads++; updateControls();
showError("");
try {
if (!options.files.length || options.files.some(file =>
file.size > 5242880 || !["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)))
throw new Error("Choose a PNG, JPEG, WebP, or GIF image up to 5 MB.");
const body = new FormData();
options.files.forEach(file => body.append("files[]", file));
const response = await fetch("/api/files", { method: "POST", body });
const ids = response.ok ? await response.json() : null;
if (!Array.isArray(ids) || ids.length !== options.files.length ||
ids.some(id => typeof id !== "string" || !id))
throw new Error(`Couldn't upload the ${label.toLowerCase()}. Please try again.`);
options.callback("success", `/api/files/${encodeURIComponent(ids[0])}`);
note(`${label} uploaded.`, "ok");
} catch (error) {
options.callback("error");
showError(error.message);
note(error.message, "error");
} finally { uploads--; updateControls(); }
});
Server code
# POST /api/files — store uploads, return their ids in the same order
def upload(request: HttpRequest) -> JsonResponse:
# Field "files[]", the name on every platform. Not request.FILES["files[]"]: that is only the last file
files = request.FILES.getlist("files[]")
if not files:
return JsonResponse({"error": 'Upload one or more files in a field named "files[]"'}, status=422)
types = [detect_type(file.read(4096)) for file in files] # by the bytes, never the client's type
for file, type in zip(files, types): # check the whole batch before storing any
if file.size > MAX_BYTES:
return JsonResponse({"error": "Each file must be 5 MB or less"}, status=422)
if type not in TYPES:
return JsonResponse({"error": f"{file.name} is not a PNG, JPEG, WebP, GIF or PDF file"}, status=422)
storage, ids = uploads(request), []
for file, type in zip(files, types):
id = str(uuid.uuid4())
storage.save(id, file) # named by id, never by the client
File.objects.create(id=id, name=file.name, type=type)
ids.append(id)
return JsonResponse(ids, safe=False)
Translate with AI
For multilingual forms, you can integrate AI in Survey Creator's Translations tab so that authors can translate titles, choices, and other form text semi-automatically.
When an author requests a translation, send the source strings and language information to your backend. The backend should call the AI provider you choose and return the translated strings in their original order. Keep the provider's API key on the server.
Authors can review and edit the translations in the UI before using them in the form.
Client code
// Return translated strings in the original order, and always finish the callback
creator.onMachineTranslate.add(async (_, options) => {
showError("");
try {
const response = await fetch("/api/translate", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ strings: options.strings, from: options.fromLocale, to: options.toLocale })
});
if (!response.ok) throw await responseError(response, "AI translation failed. Please try again.");
const strings = await response.json();
if (!Array.isArray(strings) || strings.length !== options.strings.length || strings.some(text => typeof text !== "string"))
throw new Error("The translation provider returned an invalid result. Please try again.");
options.callback(strings);
} catch (error) {
options.callback([]);
showError(`${translationError(error)} Existing translations are kept.`);
note(error.message, "error");
}
});
Server code
# POST /api/translate — strings in, translated strings out (same order); nothing goes to SurveyJS
async def translate(request: HttpRequest) -> JsonResponse:
if not settings.AI_API_KEY:
return JsonResponse({"error": "Set AI_API_KEY to enable translation"}, status=501)
body = read_json(request)
strings = body.get("strings", []) if isinstance(body, dict) else None
if not isinstance(strings, list) or not all(isinstance(text, str) for text in strings):
return JsonResponse({"error": "Expected { strings, from, to }"}, status=400)
translated = await AiTranslation().translate(strings, body.get("from", ""), body.get("to", "")) # your provider
if not isinstance(translated, list) or len(translated) != len(strings) \
or not all(isinstance(text, str) for text in translated):
return JsonResponse({"error": "The AI provider returned an unexpected answer"}, status=502)
return JsonResponse(translated, safe=False) # what options.callback() takes
Live Example: Translate with AI
Variable Presets
Form logic may depend on variables supplied by your application, such as a customer's subscription plan. Authors need sample values to test that logic before the form is used. Variable presets allow them to do that by providing named sets of those values in Survey Creator.
Load the saved presets from the backend when the editor opens. In the Preview tab, an author can select a preset to see how the form behaves with its values. Switching presets updates the preview using data already loaded in the browser.
When an author edits a preset, you need to save the updated presets to your backend as a JSON document. Check editing permission before saving, just as you do for form JSON schemas.
Client code
const creator = new SurveyCreator({
variablePresets: {
definition: {
elements: [{
type: "dropdown", name: "customerTier", title: "Customer plan",
choices: [{ value: "basic", text: "Basic" }, { value: "premium", text: "Premium" }],
isRequired: true
}]
},
presets: []
}
});
creator.onVariablePresetsChanged.add((_, options) => {
// Switching scenarios changes only Preview; editing persists the preset list
if (loaded && options.reason === "edit") { saver.changed(); saver.save(); }
});
Server code
# GET /api/variable-presets/<form_id> — return the stored preset list, or [] when none are saved
def load_presets(request: HttpRequest, form_id: str) -> HttpResponse:
presets = VariablePreset.objects.filter(key=form_id).values_list("json", flat=True).first()
return HttpResponse(presets or "[]", content_type="application/json") # as stored
# PUT /api/variable-presets/<form_id> — store the variable presets as-is: it's one JSON document
def save_presets(request: HttpRequest, form_id: str) -> HttpResponse:
if not can(request.user, "edit-forms"): # editing is an admin action: 403 otherwise
return JsonResponse({"error": "You don't have editor rights: only editors can change forms"}, status=403)
# The raw body, not request.POST: the presets are stored as they arrived, {} stays {}
VariablePreset.objects.update_or_create(key=form_id, defaults={"json": dumps(read_json(request))})
return HttpResponse(status=204)
Live Example: Variable Presets
Edit Forms Together
Several authors can work on the same form. Participants see each other's edits, selection, and cursors, and cannot edit survey elements that another participant is editing.
To let several authors work on the same form, follow these steps:
- Add
CollaborationPluginfromsurvey-creator-core/collaborationto enable this functionality. - Connect the clients to a WebSocket relay. Have the relay add each edit to a change log as a JSON record and forward it to the other participants.
- When someone joins, send them the starting JSON schema and the change log. Applying those changes brings the new participant's editor up to date.
- Save the JSON schema through
saveSurveyFuncand your usual save endpoint. After the collaboration session ends, the next session starts from the saved schema.
Client code
// Rebuild the shared form from its saved schema and ordered edit log
function initialize(message) {
creator?.dispose();
creator = new SurveyCreator({ showTranslationTab: true });
creator.JSON = message.seed;
collab = new CollaborationPlugin(creator, { roomId: formId, getInviteLink: sharedFormLink });
creator.addPlugin("collaboration", collab);
collab.setClientId(message.clientId);
configureSaving();
saver.markSaved();
if (message.log.length) collab.apply(message.log);
const append = (_, { record }) => send({ type: "append", payload: record });
collab.onRecordAdded.add(append);
collab.onRecordChanged.add(append);
collab.onStateChanged.add(() => send({ type: "presence", state: collab.getState() }));
}
Server code
# The same kind of relay as Fill Forms Together, keeping an append-only log instead of a value map:
# Creator records must be replayed in order. It runs in this app's process, on its port.
async def connect(self):
form_id, user = self.scope["url_route"]["kwargs"]["form_id"], self.scope["user"]
key = room_key.for_scope(self.scope, form_id)
if not await acan(user, "edit-forms") or not FORM_ID.match(form_id) or key is None: # like saving, editing together is for editors
await self.close() # before accept(): the browser sees a refused handshake
return
await self.accept()
self.room = await edit_room.join(key, lambda: database_sync_to_async(saved_definition)(form_id)) # seed = the saved definition
async with self.room.lock: # the log in init, then every record after it: none twice, none missed
self.participant = self.room.add(display_name(self.scope, user.get_full_name()))
await self.channel_layer.group_add(self.room.group, self.channel_name)
await self.send(text_data=dumps({"type": "init", "clientId": self.participant.id, "colorIndex": self.participant.slot,
"color": self.room.color(self.participant), "seed": self.room.seed,
"log": self.room.log})) # init first
if peers := self.room.roster(self.participant):
await self.send(text_data=dumps({"type": "presence-sync", "peers": peers}))
async def receive(self, text_data=None, bytes_data=None):
message = parse(text_data) # records stay opaque: {} is relayed as {}
if not isinstance(message, dict):
return
if message.get("type") == "append" and message.get("payload") is not None: # append, then fan out
async with self.room.lock:
self.room.log.append(message["payload"])
await self.broadcast({"type": "record", "from": self.participant.id, "payload": message["payload"]})
elif message.get("type") == "presence" and message.get("state") is not None and len(text_data) <= 4096:
self.participant.state = message["state"]
await self.broadcast({"type": "presence", "peer": self.room.peer(self.participant)})
# unknown types: ignore
async def disconnect(self, code):
if hasattr(self, "participant"): # presence-leave to the others; the log lives until the room empties
edit_room.leave(self.room, self.participant)
await self.broadcast({"type": "presence-leave", "clientId": self.participant.id})
await self.channel_layer.group_discard(self.room.group, self.channel_name)
Live Example: Edit Forms Together
Run Server-Side Workflows
Some workflows need SurveyJS logic on the server. You may need to check a submission before storing it, find problems in a form JSON schema, create a PDF, or read answers from a document.
These operations run in Node.js. A Node.js backend can run the components directly; other backends can call a Node.js service over HTTP. In either case, your backend supplies the required data and uses the result in its own workflow.
Validate Responses
Browser validation helps respondents correct their answers while filling out a form. Your API can also receive requests that bypass the form, so you need to repeat validation on the server before storing a response.
When a submission arrives, load the form JSON schema from your storage. Validate the submitted answers against that schema on the server, checking required questions, value types, and allowed choices.
Save the response only if validation succeeds. If it fails, return the errors to the client so that the respondent can correct the answers.
Client code
// Confirm a save only after the backend accepts the answers and returns a response ID
survey.onComplete.add(async (sender, options) => {
lock(true);
sender.completedHtml = "<h3>Submitting your claim...</h3>";
options.showSaveInProgress();
try {
const result = await submit(sender.data);
if (result.rejected) throw new Error(result.errors.map(describe).join("; "));
sender.completedHtml = `<h3>Your claim has been saved.</h3><p>Response ID: ${result.id}</p>`;
options.showSaveSuccess();
} catch (error) {
sender.completedHtml = "<h3>Your claim hasn't been saved.</h3>";
const message = error instanceof TypeError ? "Couldn't validate the response. Please try again." : error.message;
options.showSaveError(message);
} finally { lock(false); }
});
Server code
# POST /api/responses — ask the SurveyJS service to validate, then store as usual
async def save(request: HttpRequest) -> JsonResponse:
# The raw body, not request.POST: the stored answers keep every key, {} and 1.0 (see Save Responses)
body = read_json(request)
if not isinstance(body, dict) or not isinstance(body.get("formId"), str) or not isinstance(body.get("data"), dict):
return JsonResponse({"error": "Expected { formId, data } with an answers object"}, status=400)
if (form := await Form.objects.filter(key=body["formId"]).afirst()) is None:
return JsonResponse({"error": "Unknown form"}, status=404)
surveyjs = SurveyJsService()
check = await surveyjs.post("/response", {"schema": json.loads(form.json), "response": body["data"]}, timeout=10)
answer: Any = None
with suppress(ValueError): # not JSON: fails closed below
answer = json.loads(check.content)
if check.status_code == 422 and isinstance(answer, dict) and "errors" in answer:
if "warnings" in answer: # the stored definition itself has errors
surveyjs.unexpected("/response", check, "The stored definition has errors")
return JsonResponse({"errors": answer["errors"]}, status=400) # the answers don't fit the definition
if check.status_code != 200 or answer != {}: # fail closed: only exactly {} means valid
surveyjs.unexpected("/response", check)
return JsonResponse({"id": await ainsert_response(body["formId"], body["data"])}, status=201) # 1.0 stays 1.0
Live Example: Validate Responses
Lint JSON Schemas
A form JSON schema can contain mistakes that stop its questions or logic from working as intended. For example, a condition may refer to a question that does not exist. Check JSON schemas using the SurveyJS Linter before saving and return its findings to Survey Creator so that authors can fix these problems before respondents encounter them.
Client code
// Display the server's errors and warnings and return the actual save result to Creator
async function saveDefinition(definition) {
const response = await fetch(`/api/forms/${formId}`, {
method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(definition)
});
const report = response.status === 204 ? {} : await response.json();
reportFindings(report);
if (response.status === 422 && Array.isArray(report.errors) && report.errors.length) {
note("Form schema not saved. Fix the reported errors and retry.", "error");
return false;
}
if (!response.ok) throw new Error(report.error || "Couldn't save the form schema. Please try again.");
const count = report.warnings?.length ?? 0;
note(count ? `Schema saved with ${count} warning${count === 1 ? "" : "s"}. Review the findings above.` : "Form schema saved successfully.", "ok");
return true;
}
creator.saveSurveyFunc = async (saveNo, callback) => callback(saveNo, await checkAndSave(creator.JSON));
Server code
# PUT /api/forms/<id> — lint the definition from Creator before storing it
async def put_form(request: HttpRequest, form_id: str) -> HttpResponse:
if not await acan(await request.auser(), "edit-forms"):
return JsonResponse({"error": "You don't have editor rights: only editors can change forms"}, status=403)
definition = read_json(request) # the raw body keeps {} as {} (see Load and Save Form JSON Schemas)
surveyjs = SurveyJsService()
lint = await surveyjs.post("/schema", definition, timeout=10)
answer: Any = None
with suppress(ValueError): # not JSON: fails closed below
answer = json.loads(lint.content)
if lint.status_code == 422 and isinstance(answer, dict) and {"errors", "warnings"} <= answer.keys():
return JsonResponse(answer, status=422) # errors: refuse the save, report them as they are
warnings_only = lint.status_code == 200 and isinstance(answer, dict) and list(answer) == ["warnings"]
if not warnings_only and (lint.status_code != 200 or answer != {}): # fail closed: nothing else is clean
surveyjs.unexpected("/schema", lint)
await Form.objects.aupdate_or_create(key=form_id, defaults={"json": dumps(definition)}) # 1.0 stays 1.0
return JsonResponse({"warnings": answer["warnings"]}) if warnings_only else HttpResponse(status=204) # warnings don't block it
Live Example: Lint JSON Schemas
Generate PDFs
A backend workflow may need a PDF for an archive or email attachment. SurveyJS PDF Generator can create the document on the server without opening a browser.
Load the form JSON schema and, for a completed form, its saved answers. Pass them to PDF Generator to create the document. Your backend can then store the PDF, attach it to an email, or send it to the browser with the application/pdf content type.
Client code
// Open a tab during the click and navigate only after the server returns a PDF
async function generatePdf(id, action) {
if (urls.has(id)) return usePdfUrl(id, action, urls.get(id));
const tab = action === "open" ? window.open("/examples/server-pdf/loading", "_blank") : null;
try {
const response = await fetch(`/api/claims/${id}/pdf`);
if (!response.ok) throw await responseError(response, "Couldn't generate the PDF. Please try again.");
if (!response.headers.get("content-type")?.startsWith("application/pdf")) throw new Error("The server didn't return a PDF. Please try again.");
const blob = await response.blob();
if (!blob.size) throw new Error("The server returned an empty PDF. Please try again.");
const url = URL.createObjectURL(blob);
urls.set(id, url);
if (action === "download") return usePdfUrl(id, action, url);
const opened = tab && !tab.closed;
if (opened) tab.location = url;
return { message: opened ? "PDF opened in a new tab." : "PDF ready. Select Open PDF again or Download PDF.", needsAction: !opened };
} catch (error) { tab?.close(); throw error; }
}
Server code
# GET /api/claims/<id>/pdf — ask the SurveyJS service for the filled form and pass the PDF through
async def claim_pdf(request: HttpRequest, claim_id: int) -> HttpResponse:
if (claim := await Response.objects.filter(form_id="claim", id=claim_id).afirst()) is None:
return JsonResponse({"error": "Unknown claim"}, status=404)
match claim.definition_version: # use the schema version recorded with the response
case "v1" | "v2" as version:
definition = (DEFINITIONS / f"relational-storage.{version}.json").read_text(encoding="utf-8")
case None:
definition = (await Form.objects.aget(key="claim")).json
case _:
return JsonResponse({"error": "The schema version for this claim is unavailable"}, status=409)
surveyjs = SurveyJsService()
pdf = await surveyjs.post("/pdf", {"schema": json.loads(definition), "response": json.loads(claim.data)}, timeout=60)
if (pdf.status_code != 200 or not pdf.headers.get("content-type", "").startswith("application/pdf")
or not pdf.content.startswith(b"%PDF-")):
surveyjs.unexpected("/pdf", pdf)
return HttpResponse(pdf.content, content_type="application/pdf", headers={
"Content-Disposition": f'inline; filename="claim-{claim_id}.pdf"', "Cache-Control": "private, no-store"})
Extract Responses from Documents
Some responses arrive as completed paper forms, scans, or PDFs. AI Form Response Extractor can use your form JSON schema to read those documents and return answers in the same format as an online response.
Upload the document to your backend and send it, along with the JSON schema, to the extractor. The extractor calls the AI provider you configure and returns the answers with confidence information. It can also return a unique ID detected in the document, such as an ID from a QR code.
Use the returned answers to fill a draft form. Show which answers need checking so a person can review and correct them before submitting. Extraction itself does not save a response—save the reviewed answers through your usual endpoint.
Client code
// Extract a draft without saving it and validate the response before replacing any answers
async function extract(file, signal) {
const body = new FormData();
body.append("scan", file);
const response = await fetch("/api/work-orders/extract", { method: "POST", body, signal });
if (!response.ok) throw await responseError(response, "Couldn't extract the answers. Try again or enter the answers directly in the form.");
const result = await response.json();
if (!result.answers || typeof result.answers !== "object" || Array.isArray(result.answers) || !Array.isArray(result.confidence)) {
throw new Error("The extraction result couldn't be read. Try again or enter the answers directly in the form.");
}
return result;
}
Server code
# POST /api/work-orders/extract — send the uploaded scan to the SurveyJS service; return a draft response
async def extract_work_order(request: HttpRequest) -> JsonResponse:
if (scan := request.FILES.get("scan")) is None and "scan" not in request.POST:
return JsonResponse({"error": 'Upload the scan in a field named "scan"'}, status=400)
if scan is None or scan.size > MAX_BYTES: # a text field named "scan" isn't a file
return JsonResponse({"error": "The scan must be a file of 5 MB or less"}, status=413)
if detect_type(raw := scan.read()) is None: # by the first bytes, never the client's Content-Type
return JsonResponse({"error": "The file is not a PDF, PNG, JPEG, WebP or GIF document"}, status=400)
schema = json.loads((await Form.objects.aget(key="work-order")).json)
surveyjs = SurveyJsService()
out = await surveyjs.post("/extract", {"schema": schema, "document": base64.b64encode(raw).decode()}, timeout=120)
result: Any = None
with suppress(ValueError): # JSON with base64 went out, not multipart; an answer that isn't JSON fails closed
result = json.loads(out.content)
match out.status_code, result: # nothing is saved: a person reviews the draft
case 200, {"data": dict() as answers}:
return JsonResponse({"answers": answers, "confidence": result.get("confidence", []), "uniqueId": result.get("uniqueId")})
case 400, {"error": "INVALID_DOCUMENT"}:
return JsonResponse({"error": "The file is not a PDF, PNG, JPEG, WebP or GIF document"}, status=400)
case 503, {"error": "AI_NOT_CONFIGURED"}:
return JsonResponse({"error": "The SurveyJS service has no AI provider configured"}, status=503)
case 502, {"error": "EXTRACTION_FAILED"}:
return JsonResponse({"error": "Could not extract the response from the document"}, status=502)
surveyjs.unexpected("/extract", out, log_body=False) # fail closed, logged by status only
Send feedback to the SurveyJS team
Need help? Visit our support page