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

2.1k Views Asked by At

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)
2

There are 2 best solutions below

0
On

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

class UserModel(TortoiseBaseUserModel):
    name = fields.CharField()
0
On

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)