I found that Django Ninja uses Pydantic. I have created a Schema from Django model,
class UserSchema(ModelSchema):
class Config:
model = User
model_fields = ["username", "first_name", "last_name", "email"]
class CreateUserSchema(UserSchema):
password: str
and I used CreateUserSchema
in my view, and import EmailStr
from Pydantic
...
async def register(request, user_data: schemas.CreateUserSchema):
email = EmailStr(user_data.pop("email"))
...
I want to validate EmailField
but, it cannot validate, and store anything in the field. How can if fix it?
I see a similar issue in django-ninja: ModelSchema automatical validation #443 . It is currently open and has a similar topic; namely apply model field validation automatically for ModelSchema(s).
So, until a more general solution is found I suggest calling your Django model's clean()
method inside your request handler:
from django.core.exceptions import ValidationError
from ninja.errors import ValidationError as NinjaValidationError
...
class UserSchema(ModelSchema):
class Config:
model = User
model_fields = ["username", "first_name", "last_name", "email"]
...
# and in your incoming request handler
@router.post('/example')
def register(request, payload: UserSchema):
user = models.User(**payload.dict())
try:
user.clean()
except ValidationError as err:
raise NinjaValidationError(err.messages)
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.