Click here to Skip to main content
15,847,750 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I hope everyone are safe and fine. I am trying this code to make it work. I have a main.py file and models.py file where I have a Class User created in the models.py file and I am trying to import the User class from models.py file to main.py file. I a using Tortoise ORM for this purpose. I am getting an error "ImportError: cannot import name 'register_tortoise' from 'tortoise.contrib.pydantic'" in the command prompt


**main.py**

<pre lang="Python">from fastapi import FastAPI, Request, Form, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from models import User_Pydantic, UserIn_Pydantic, User
from tortoise.contrib.pydantic import register_tortoise, HTTPNotFoundError



app = FastAPI()


register_tortoise(
    app,
    db_url="sqlite://store.db",
    modules={'models':['models']},
    generate_schemas = True,
    add_exception_handlers = True

)

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")



@app.get("/", response_class=HTMLResponse)
async def login_page(request :Request):
    return templates.TemplateResponse("index.html", {"request":request})


@app.post("/loginsuccess/", response_class=HTMLResponse)
async def login_success(request: Request, username: str = Form(...), password: str = Form(...)):

    if username=='michael' and password=='clarke':
        return templates.TemplateResponse("homepage.html", {"request": request, "username":username})
    else:
        status_code:int
        status_code = 500
        return templates.TemplateResponse("index.html", {"request":request, "status_code":status_code})




**models.py**

from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator

class User(Model):
    id = fields.CharField(pk=True, max_length=50)
    username = fields.CharField(max_length=50, unique=True)
    password = fields.CharField(max_length=50, null=True)


    class PydanticMeta:
        pass 

User_Pydantic = pydantic_model_creator(User, name="User")
UserIn_Pydantic = pydantic_model_creator(User, name="UserIn", exclude_readonly=True)


What I have tried:

I have tried but i am getting an error
"ImportError: cannot import name 'register_tortoise' from 'tortoise.contrib.pydantic'"
Posted
Updated 24-May-21 23:51pm

1 solution

 
Share this answer
 
Comments
Sagabarnisa S 25-May-21 5:24am    
its not working
Richard MacCutchan 25-May-21 6:07am    
Well I have no idea what that is supposed to mean.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900