Author Functionality

With user functionality now added to the project, there are now users available. Each blog post should have an author. Time to refactor the schemas to include the author of a blog post.

Because we’re only allowing authenticated authors to access the Create, Update and Delete views, we can take the current user’s ID as the author of a blogpost.

The following change will allow us to have a One-To-Many relationship, a user can have many blogposts:

Each blogpost will have one author (a Many-To-One relation to a user), stored as the User primary key in a foreign key column on the blog post:

Schemas#

In the BlogPost table model, add an blogpost_author_id foreign key column, and a blogpost_author relationship:

db/schemas/blog_schemas.pypython
from typing import TYPE_CHECKING  # NEW

from pydantic import ConfigDict
from sqlmodel import SQLModel, Field, Relationship  # UPDATED

if TYPE_CHECKING:  # NEW
    from db.schemas.user_schemas import User  # NEW
db/schemas/blog_schemas.pypython
class BlogPostOut(BlogPostIn):
    id: uuid.UUID
    created_date: datetime.datetime
    blogpost_author_id: uuid.UUID | None  # NEW

# SQLModel Database Schemas
class BlogPost(BlogPostIn, table=True):
    id: uuid.UUID = Field(
        default_factory=uuid.uuid4,
        primary_key=True)
    created_date: datetime.datetime = Field(
        default_factory=lambda: datetime.datetime.now(datetime.UTC))
    blogpost_author_id: uuid.UUID | None = Field(default=None, foreign_key="user.id")  # NEW
    blogpost_author: "User" = Relationship(back_populates="blogposts")  # NEW

A few design decisions here:

  • The author’s id goes only on the table model (and the output schema), not on BlogPostIn. BlogPostIn is what an API accepts, so if it included the author, whoever called the API could claim any author they liked, and the update API (which copies every field of BlogPostIn onto the post) would replace the author on every edit. The author is always set from the logged-in user instead.
  • blogpost_author_id can be None. Posts created before this change have no author, and a database can’t add a required column to rows that already exist (as we saw with teaser in the Alembic section).
  • foreign_key="user.id" tells the database the value must be the id of a row in the user table.
  • Relationship() doesn’t add a column. It lets you write post.blogpost_author to get the User object, and SQLModel loads it from the database when needed. back_populates links it to the matching relationship on User.
  • Any script that uses the blog schemas on its own, such as db/seed.py, now needs to import db.schemas.user_schemas as well, so SQLAlchemy knows what "User" refers to: import db.schemas.user_schemas # noqa: F401. The application itself always imports both.
  • The User import is only for type checkers (TYPE_CHECKING is False at runtime), and the annotation is the string "User". That avoids a circular import, since user_schemas.py imports from blog_schemas.py.

Then add the other side of the relationship, a blogposts list, to User, and to UserOut so the API includes a user’s posts:

db/schemas/user_schemas.pypython
from sqlmodel import SQLModel, Field, Relationship  # UPDATED

from db.schemas.blog_schemas import BlogPost, BlogPostOut  # NEW
db/schemas/user_schemas.pypython
class UserOut(SQLModel):
    # ... the existing fields ...
    created_date: datetime.datetime
    blogposts: list[BlogPostOut] = []  # NEW
db/schemas/user_schemas.pypython
class User(SQLModel, table=True):
    # ... the existing fields ...
    created_date: datetime.datetime = Field(
        default_factory=lambda: datetime.datetime.now(datetime.UTC))
    blogposts: list[BlogPost] = Relationship(back_populates="blogpost_author")  # NEW

Naming constraints#

Before creating the migration, there’s one more thing to set up. A foreign key is a database constraint, and to change or remove a constraint later, Alembic needs to know its name. SQLModel doesn’t name foreign keys by default, and on SQLite, where Alembic’s batch mode rebuilds the table, the migration fails with:

ValueError: Constraint must have a name
note

Earlier versions of this guide suggested deleting the database and starting over at this point. Naming the constraints fixes the problem properly.

The fix is a naming convention: a pattern SQLAlchemy uses to name every constraint automatically. It must be set before any table is defined, so put it in db/schemas/__init__.py, which Python runs as soon as anything in db/schemas is imported:

db/schemas/__init__.pypython
from sqlmodel import SQLModel

# Give every constraint a predictable name. Alembic needs named constraints to
# change them later, and SQLite's "batch mode" refuses unnamed ones.
SQLModel.metadata.naming_convention = {
    "ix": "ix_%(column_0_label)s",
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}

This is the convention recommended by the Alembic documentation. For example, the new foreign key will be named fk_blogpost_blogpost_author_id_user.

Migration#

Create a new Alembic revision:

alembic revision --autogenerate -m "added post authors"

Read the generated file as always: the new column is nullable, and the foreign key now has a name:

    with op.batch_alter_table('blogpost', schema=None) as batch_op:
        batch_op.add_column(sa.Column('blogpost_author_id', sa.Uuid(), nullable=True))
        batch_op.create_foreign_key(batch_op.f('fk_blogpost_blogpost_author_id_user'), 'user', ['blogpost_author_id'], ['id'])
alembic upgrade head
tip

The example code does this together with the comments in the next section, in one migration called “added post authors and comments”.

Recording the author#

The API function for creating posts takes the author’s id as a separate argument:

api/blog_apis.pypython
@router.post('/blog/create', status_code=status.HTTP_201_CREATED)
def create_blogpost_api(blogpost_in: BlogPostIn, author_id: uuid.UUID | None = None,
                        session: Session = Depends(get_session_db)) -> BlogPostOut:
    new_blogpost = BlogPost.model_validate(blogpost_in, update={"blogpost_author_id": author_id})  # UPDATED
    session.add(new_blogpost)
    session.commit()
    session.refresh(new_blogpost)
    return new_blogpost

When this is called as an API, author_id becomes an optional query parameter (/api/v1/blog/create?author_id=...). The blogpost_create_post_view passes the logged-in user:

web/views/blog_views.pypython
    post = create_blogpost_api(blogpost_in=new_blogpost, author_id=current_user.id, session=session)  # UPDATED

The update view doesn’t need to change: update_blogpost_api only copies the fields in BlogPostIn, so the author stays as it was.

You can now experiment with the application: log in as an author and create a blogpost or two. Then, via http://localhost:8000/docs (with CONF_ENABLE_APIS=true), use the “Get User By Id Api” API, and see that the blogposts created by that user are returned in a list called blogposts, for example:

{
  "id": "cebb000b-e9d9-4c71-91a6-ef2b3dabd5fa",
  "first_name": "John",
  "last_name": "Doe",
  "email": "jdoe@email.com",
  "username": "jdoe@email.com",
  "profile_image": "/static/img/profile.jpg",
  "is_superuser": true,
  "is_active": true,
  "is_author": true,
  "is_member": false,
  "created_date": "2026-12-02T14:07:42.490805Z",
  "blogposts": [
    {
      "title": "At vero eos",
      "teaser": "At vero eos et accusamus et iusto odio dignissimos ducimus",
      "content": "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident...",
      "cover_image": "/uploads/0bfcdbb7-f759-4524-b1eb-8badff4a2423.jpg",
      "published": true,
      "id": "76ef90d6-7981-4c3e-8c49-73b1e9d225f9",
      "created_date": "2026-12-02T14:08:56.832733Z",
      "blogpost_author_id": "cebb000b-e9d9-4c71-91a6-ef2b3dabd5fa",
      "comments": []
    }
  ]
}

(The comments list comes in the next section.)

Update the blogpost.html template to display who wrote the post, if it has an author:

web/templates/blogpost.htmljinja
<span class="meta">Posted on {{ context.post.created_date.strftime('%d %B %Y') }}{% if context.post.blogpost_author %}
    by {{ context.post.blogpost_author.first_name }} {{ context.post.blogpost_author.last_name }}{% endif %}</span>

Only the owner can edit#

So far any author can edit or delete any post. In the blogpost_get_view, work out whether the logged-in user wrote the post:

web/views/blog_views.pypython
    current_user = is_user(request, session)
    post = get_blogpost_by_id_api(id=id, session=session)
    blogpost_owner = current_user is not None and post.blogpost_author_id == current_user.id  # NEW
web/views/blog_views.pypython
        "user": current_user,
        "blogpost_owner": blogpost_owner,  # NEW

Both ids are uuid.UUID objects, so they can be compared directly with ==.

Then only show the Edit and Delete buttons to the owner:

web/templates/blogpost.htmljinja
                     {% if context.blogpost_owner %}
                     <br>
                     <a href="/blog/update/{{ context.post.id }}" class="btn btn-default">Edit</a>
                     <form action="/blog/delete/{{ context.post.id }}" method="post" style="display: inline"
                           onsubmit="return confirm('Are you sure?')">
                         <button type="submit" class="btn btn-default">Delete</button>
                     </form>
                     {% endif %}

However, an author could still go to the update URL, or send the update or delete form directly, for any blogpost. So the same check is needed in blogpost_update_get_view, blogpost_update_post_view and blogpost_delete_post_view, after the existing login and author checks:

web/views/blog_views.pypython
    post = get_blogpost_by_id_api(id=id, session=session)
    if post.blogpost_author_id != current_user.id:
        return RedirectResponse(f'/blog/{id}', status_code=status.HTTP_303_SEE_OTHER)

For example, the delete view becomes:

web/views/blog_views.pypython
@router.post('/blog/delete/{id}', response_class=HTMLResponse)
def blogpost_delete_post_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):
    current_user = is_user(request, session)
    if current_user is None:
        return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
    if not current_user.is_author:
        return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
    post = get_blogpost_by_id_api(id=id, session=session)
    if post.blogpost_author_id != current_user.id:
        return RedirectResponse(f'/blog/{id}', status_code=status.HTTP_303_SEE_OTHER)
    delete_blogpost_by_id_api(id=id, session=session)
    return RedirectResponse('/', status_code=status.HTTP_303_SEE_OTHER)

The project is now in a fairly complete state. The next section, for adding comments, reinforces this pattern of adding a database schema and including relationships.