1

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?

CC7052
  • 563
  • 5
  • 16
  • Assume this `register` is an endpoint-method. What happens if you remove the `async`? Using the model-type for body-parameters should trigger automatic validation like explained in [Django Ninja: How-To Guides > Parsing Input > Request Body](https://django-ninja.rest-framework.com/guides/input/body/?h=validate#results). – hc_dev Jan 29 '23 at 12:09

2 Answers2

1

A simple way using django-ninja and pydantic (pydantic needs to be installed with the email flag: pip install pydantic[email]) is following:

class UserSchema(ModelSchema):
    email: EmailStr

    class Config:
        model = User
        model_fields = ["username", "first_name", "last_name", "email"]


class CreateUserSchema(UserSchema):
    password: str

So it will validate the email directly in schema validation

FabianClemenz
  • 303
  • 3
  • 8
0

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() or even full_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)
    ...
Florin C.
  • 593
  • 4
  • 13