Dashboard

The first step is to add the layout and the dashboard page for site administration.

Layout#

Add a small stylesheet for the admin layout:

web/static/css/admin.csscss
/* Site admin: a dark sidebar beside the page content, on top of Bootstrap 3 */
body { background: #f5f6f8; }
.admin-topbar { background: #222; color: #fff; padding: 12px 20px; }
.admin-topbar a { color: #fff; margin-left: 18px; }
.admin-topbar .brand { font-weight: 700; margin-left: 0; }
.admin-layout { display: flex; min-height: calc(100vh - 46px); }
.admin-sidebar { width: 220px; background: #2f3640; padding-top: 12px; flex-shrink: 0; }
.admin-sidebar a { display: block; color: #cfd6df; padding: 10px 20px; }
.admin-sidebar a:hover, .admin-sidebar a.active { background: #3d4652; color: #fff; text-decoration: none; }
.admin-content { flex: 1; padding: 24px 32px; min-width: 0; }
.admin-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 16px; }
.admin-card { background: #fff; border: 1px solid #e1e4e8; border-radius: 6px; padding: 16px; }
.admin-card .number { font-size: 32px; font-weight: 700; }
.admin-content table { background: #fff; }
.admin-content td form { display: inline; margin: 0; }

Create a directory for the admin templates:

mkdir web/templates/admin

Add the base template for the admin pages. It uses Bootstrap and Font Awesome from the Clean Blog theme’s vendor directory, and the new stylesheet:

web/templates/admin/_base.htmljinja
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Site Admin · ExampleForYou</title>
    <link href="/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="/static/css/admin.css" rel="stylesheet">
</head>
<body>

<div class="admin-topbar">
    <a class="brand" href="/admin">ExampleForYou Admin</a>
    <span class="pull-right">
        {{ context.user.first_name }} {{ context.user.last_name }}
        <a href="/">Website</a>
        <a href="/auth/logout">Logout</a>
    </span>
</div>

<div class="admin-layout">
    <nav class="admin-sidebar">
        <a href="/admin" {% if context.page == 'admin' %}class="active"{% endif %}><i class="fa fa-dashboard fa-fw"></i> Dashboard</a>
        <a href="/admin/users" {% if context.page == 'users' %}class="active"{% endif %}><i class="fa fa-users fa-fw"></i> Users</a>
        <a href="/admin/comments" {% if context.page == 'comments' %}class="active"{% endif %}><i class="fa fa-comments fa-fw"></i> Comments</a>
        <a href="/admin/blogposts" {% if context.page == 'blogposts' %}class="active"{% endif %}><i class="fa fa-file-text fa-fw"></i> Blog Posts</a>
    </nav>
    <main class="admin-content">
        {% block content %}
        {% endblock %}
    </main>
</div>

</body>
</html>

The sidebar highlights the current page, using the page in each view’s context, as the main site’s navigation does.

Superusers only#

Every admin view starts by checking the user is a superuser, so add a helper for it in a new views file:

web/views/admin_views.pypython
import uuid

from fastapi import APIRouter, Depends, Form, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlmodel import Session

from api.admin_apis import (delete_any_comment_api, delete_user_by_id_api, get_all_blogposts_api,
                            get_all_comments_api, get_all_users_api, get_site_counts_api,
                            update_blogpost_published_api, update_comment_approval_api, update_user_api)
from api.auth_apis import is_user
from api.blog_apis import delete_blogpost_by_id_api
from db.db import get_session_db
from db.schemas.user_schemas import User, UserUpdate

router = APIRouter()

templates = Jinja2Templates('web/templates')

def get_superuser(request: Request, session: Session) -> User | None:
    """The logged-in user if they're a superuser, otherwise None."""
    current_user = is_user(request, session)
    if current_user is None or not current_user.is_superuser:
        return None
    return current_user

def not_allowed() -> RedirectResponse:
    return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)

Non-superusers, including visitors who aren’t logged in, are simply sent to the home page.

Dashboard#

The dashboard shows a few counts, from a new admin API file:

api/admin_apis.pypython
import uuid

from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel import Session, delete, func, select

from db.db import get_session_db
from db.schemas.blog_schemas import BlogPost, BlogPostOut, Comment, CommentOut
from db.schemas.user_schemas import AuthToken, User, UserOut, UserUpdate

router = APIRouter()

# Dashboard
def get_site_counts_api(session: Session) -> dict[str, int]:
    def count(query) -> int:
        return session.exec(query).one()
    return {
        "users": count(select(func.count()).select_from(User)),
        "blogposts": count(select(func.count()).select_from(BlogPost)),
        "comments": count(select(func.count()).select_from(Comment)),
        "comments_pending": count(select(func.count()).select_from(Comment).where(Comment.approved == False)),
    }

select(func.count()).select_from(User) asks the database to count the rows, which is much quicker than loading every user just to count them.

web/views/admin_views.pypython
# Dashboard
@router.get('/admin', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def admin_view(*, request: Request, session: Session = Depends(get_session_db)):
    current_user = get_superuser(request, session)
    if current_user is None:
        return not_allowed()

    context = {
        "page": "admin",
        "user": current_user,
        "counts": get_site_counts_api(session),
    }

    return templates.TemplateResponse(request, 'admin/admin.html', {'context': context})
web/templates/admin/admin.htmljinja
{% extends "admin/_base.html" %}

{% block content %}
<h2>Dashboard</h2>
<hr>
<div class="admin-cards">
    <a class="admin-card" href="/admin/users"><div class="number">{{ context.counts.users }}</div>Users</a>
    <a class="admin-card" href="/admin/blogposts"><div class="number">{{ context.counts.blogposts }}</div>Blog posts</a>
    <a class="admin-card" href="/admin/comments"><div class="number">{{ context.counts.comments }}</div>Comments</a>
    <a class="admin-card" href="/admin/comments"><div class="number">{{ context.counts.comments_pending }}</div>Comments awaiting approval</a>
</div>
{% endblock %}

Add both routers to main.py. The admin APIs go with the other APIs, so they’re only available when CONF_ENABLE_APIS is on (they have no login checks of their own):

main.pypython
from api import health_api, blog_apis, captcha_apis, auth_apis, admin_apis  # UPDATED
from web.views import home_view, blog_views, contact_view, auth_views, admin_views  # UPDATED
main.pypython
    if settings.CONF_ENABLE_APIS:
        main_app.include_router(blog_apis.router, prefix=settings.CONF_API_V1_STR, tags=["blog_apis"])
        main_app.include_router(auth_apis.router, prefix=settings.CONF_API_V1_STR, tags=["auth_apis"])
        main_app.include_router(admin_apis.router, prefix=settings.CONF_API_V1_STR, tags=["admin_apis"])  # NEW
main.pypython
    main_app.include_router(admin_views.router, tags=["web_views"])  # NEW

Finally, add an Admin link to the main site’s navigation in _base.html, only for superusers, before the Logout link:

web/templates/_base.htmljinja
                    {% if context.user.is_superuser %}
                    <li>
                        <a href="/admin">Admin</a>
                    </li>
                    {% endif %}

Log in as a superuser, and you now have an /admin page where we can add views for managing the site: