Home > Software design >  ValidationError for datetime
ValidationError for datetime

Time:10-08

Hi thank you for reading the long post. I'm learning FastAPI-SQLAlchemy-PostgresSQL. I'm following the tutorial to code a demo project. My database is created like this:

CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    title text,
    content text,
    owner_id integer REFERENCES users(id),
    date_created timestamp without time zone,
    date_last_updated timestamp without time zone
);

-- Indices -------------------------------------------------------

CREATE UNIQUE INDEX posts_pkey ON posts(id int4_ops);

My SQLAlchemy Models looks like this:

class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    content = Column(String, index=True)
    owner_id = Column(Integer, ForeignKey('users.id'))
    date_created = Column(DateTime, default=dt.datetime.now)
    date_last_updated = Column(DateTime, default=dt.datetime.now)

    owner = relationship("User", back_populates="posts")

And the Pydantic Schema looks like this:

class PostBase(BaseModel):
    title: str
    content: str


class PostCreate(PostBase):
    pass


class Post(PostBase):
    id: int
    owner_id: int
    date_create: dt.datetime
    date_last_updated: dt.datetime

    class Config:
        orm_mode = True

Finally I create a post with this:

def create_post(db: Session, post: schemas.PostCreate, user_id: int):
    post = models.Post(**post.dict(), owner_id=user_id)
    db.add(post)
    db.commit()
    db.refresh(post)
    return post

@app.post("/users/{user_id}/posts", response_model=schemas.Post)
def create_post(user_id: int, post: schemas.PostCreate, db: Session = Depends(get_db)):
    user = crud.get_user(user_id=user_id, db=db)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return create_post(db=db, post=post, user_id=user_id)

I can see that the post is created correctly in the database: | id | title|content|owner_id|date_created |date_last_updated | | -- | -----|-------|--------|--------------------------|-------------------------| | 3 | hi |hi |3 |2021-10-08 03:00:43.731416|2021-10-08 03:00:43.73143|

But the console print the following error and no JSON is returned from the API

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 580, in __call__
    await route.handle(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 241, in handle
    await self.app(scope, receive, send)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 52, in app
    response = await func(request)
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 234, in app
    response_data = await serialize_response(
  File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 137, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Post
response -> date_create
  field required (type=value_error.missing)

CodePudding user response:

pydantic.error_wrappers.ValidationError: 1 validation error for Post

response -> date_create field required (type=value_error.missing)

here is your error, you arent filling one field, and is required for the form.

check if "date_created" is required in your form

  • Related