For Form data, I defined class as mentioned here /a/60670614/6189499. Using pydantic v2, pydantic model is defined as
@as_form
class Test(BaseModel):
param1: str
c: bool = False
@field_validator('c',mode='before')
@classmethod
def convert_to_bool(cls, v):
print("hello inside bool")
if isinstance(v, str):
if v.lower() in {'true', 'True'}:
return True
elif v.lower() in {'false', 'False'}:
return False
return v
from fastapi import Depends, Form
@router.post('/me')
async def me(request: Request, form: Test = Depends(Test.as_form)):
return form
Sending formdata, ‘c’ from basemodel is always string and field_validation is not executed. How to casting that string value ‘c’ to boolean?
I tried this
@as_form
class Test(BaseModel):
param1: str
c: string= "False"
@field_validator('c',mode='before')
@classmethod
def convert_to_bool(cls, v):
print("hello inside bool")
if isinstance(v, str):
if v.lower() in {'true', 'True'}:
return True
elif v.lower() in {'false', 'False'}:
return False
return v
This also doesn’t execute validation check.