pythonpydanticdjango-ninja

Email Validator in Django Ninja


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?


Solution

  • 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