Home > OS >  FastAPI Request body returns 'null' from 'checkbox' HTML Tag
FastAPI Request body returns 'null' from 'checkbox' HTML Tag

Time:07-22

Checkbox returns 'null' value

I'm having an issue with FastAPI request body return 'null' value from a checkbox when the checkbox isn't checked but on the otherhand when it's checked it returns True.


Error after POST request

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


Main class

@app.post("/job/create")
async def job_create(request: Request, response: Response, job: JobSchema = Depends(JobSchema.as_form), db: Session = Depends(get_db)):
    job_ = models.Job(name=job.name, description=job.description, is_active=job.is_active)
    db.add(job_)
    db.commit()
    db.refresh(job_)
    url = f"/job/{job_.id}"
    response = RedirectResponse(url=url)
    return response

Schema class

class JobSchema(BaseModel):
    name: str
    description: str
    is_active: bool = False

    @classmethod
    def as_form(cls, name: str = Form(...), description: str = Form(...), is_active: bool = Form(...)):
        return cls(name=name, description=description, is_active=is_active)


Checkbox code

<div >
    <label for="is_active">Is Active</label>
    <input type="checkbox"  id="is_active" name="is_active"/>
</div>

Html

How would i get only True/False returns from the checkbox or is my only option to do some kind of validation on the checkbox?

CodePudding user response:

HTML checkbox elements will not send a value to your sever when the element is unchecked (see MDN docs). But your validation is requiring an is_active field be sent. So the error occurs when the checkbox is unchecked. Also, you have not provided a value attribute of the checkbox element in your HTML, so the default value would be is_active=on.

You could change your as_form() method to accept an optional is_active field, and then convert it to True if it is present and equal to on.

class JobSchema(BaseModel):
    name: str
    description: str
    is_active: bool = False

    @classmethod
    def as_form(
        cls,
        name: str = Form(...),
        description: str = Form(...),
        is_active: Union[str, None] = Form(None)
    ):
        is_active_bool = True if is_active == "on" else False
        return cls(name=name, description=description, is_active=is_active_bool)
  • Related