FastApi Users Auth, can't add extra fields for register

Viewed 1252

I'm using Fastapi, Fastapi Users and TortoiseOrm for auth on my project.

FastApi Users

Tortoise

I followed the example on FastApi Users website and when I try to add some extra fields at register users, get this error:

RuntimeError: no validator found for <class 'tortoise.fields.data.CharField'>, see arbitrary_types_allowed in Config

Here is my code, thanks for your help!

from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
from fastapi_users import models
from fastapi_users.db import TortoiseBaseUserModel, TortoiseUserDatabase
from tortoise.contrib.starlette import register_tortoise


class User(models.BaseUser):
 nombre = fields.CharField(max_length=100)
 apellidos = fields.CharField(max_length=100)


class UserCreate(models.BaseUserCreate):
  pass

class UserUpdate(User, models.BaseUserUpdate):
  pass

class UserDB(User, models.BaseUserDB):
  pass

class UserModel(TortoiseBaseUserModel):
  pass


 user_db = TortoiseUserDatabase(UserDB, UserModel)
3 Answers

To add custom properties:

from typing import Optional
from pydantic import Field

class User(models.BaseUser):
  nombre : Optional[str] = Field(max_lenght="100")
  apellidos :Optional[str] = Field(max_lenght="100")

To have these fields (nombre and apellidos) appear in your path function as properties, you will need to make changes to the fastapi_users library.

If you are using a virtual environment, there's a Lib folder that holds the installed libraries and more. Look for models.py file in the Lib/fastapi_users folder. Update the file with the new properties and do the same in the db file you are using for the project.

Happy computing!!

I faced a similar error while using FastAPI Users with SQlAlchemy. What worked for me was to add the custom fields (nombre and appelidos in your case) to each of the 4 user models AND to the UserModel table while defining it

schemas.py file

from fastapi_users import models

class User(models.BaseUser):
    sid: int
    fname: str
    lname: str
    
class UserCreate(models.BaseUserCreate):
    sid: int
    fname: str
    lname: str

class UserUpdate(User, models.BaseUserUpdate):
    sid: int
    fname: str
    lname: str
  
class UserDB(User, models.BaseUserDB):
    sid: int
    fname: str
    lname: str

models.py file

from sqlalchemy import Column, Integer, String
from fastapi_users.db import SQLAlchemyBaseUserTable
from db import Base

class UserTable(Base, SQLAlchemyBaseUserTable):
    sid = Column(Integer)
    fname = Column(String)
    lname = Column(String)

This worked for me, it requires the tortoise ORM format for the field:

class UserModel(TortoiseBaseUserModel):
    name = fields.CharField()
Related