[Python] How to submit selected value from HTML dropdown list to FastAPI backend?

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    How do I submit the value selected from an HTML dropdown list, using a FastAPI backend and an HTML-Jinja2 template in the frontend?

    Here is my code for the app so far:

    from fastapi import FastAPI, Request, Form
    from fastapi.templating import Jinja2Templates


    app = FastAPI()
    templates = Jinja2Templates(directory="templates/")


    @app.get('/')
    def read_form():
    return 'hello world'


    @app.get("/form")
    def form_post(request: Request):
    result = "Select your name"
    return templates.TemplateResponse('form.html', context={'request': request, 'result': result})


    @app.post("/form")
    def form_post(request: Request, result = Form(...)):
    return templates.TemplateResponse('form.html', context={'request': request, 'result': result})


    Here is the HTML:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Sample Form</title>
    </head>
    <body>
    <form method="post">

    <select name="names" id="names">
    <option value="n1">Name 1</option>
    <option value="n2">Name 2</option>
    <option value="n3">Name 3</option>
    <option value="n5">Name 4</option>
    </select>
    <input type="submit" value="Submit">
    </form>

    <p>Result: {{ result }}</p>

    </body>
    </html>


    Here is the error message:

    {"detail":[{"loc":["body","result"],"msg":"field required","type":"value_error.missing"}]}


    The goal is to select a name, then click submit, and finally, have it displayed below.

    Continue reading...

Compartilhe esta Página