I’m looking for guidance on how to send the chosen value from an HTML dropdown list on my frontend to my FastAPI backend.
I have set up a basic form which includes a dropdown that should transmit the selected name upon submission. However, I’m encountering an error indicating that a required field is not provided during form submission.
Here’s the FastAPI code I’m working with:
from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates/")
@app.get('/')
def home():
return 'hello'
@app.get("/form")
def display_form(request: Request):
message = "Please choose your name"
return templates.TemplateResponse('form.html', context={'request': request, 'message': message})
@app.post("/form")
def submit_form(request: Request, message = Form(...)):
return templates.TemplateResponse('form.html', context={'request': request, 'message': message})
And this is the associated HTML/Jinja2 template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Choose Your Name</title>
</head>
<body>
<form method="post">
<select name="names" id="names">
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
<option value="name3">Name 3</option>
<option value="name4">Name 4</option>
</select>
<input type="submit" value="Submit">
</form>
<p>Selected Name: {{ message }}</p>
</body>
</html>
Whenever I submit, I encounter this error:
{"detail":[{"loc":["body","message"],"msg":"field required","type":"value_error.missing"}]}
I would like to select a name from the dropdown, click submit, and see my choice displayed on the page. How can I resolve this issue between the HTML form and the FastAPI backend?