User Image
NotesWe haven’t done anything with the user profile image yet. In fact, the eagle-eyed among you might have noticed that the default image, /static/img/profile.jpg, doesn’t exist.
A default image#
Add a default profile image, a generic user silhouette, as web/static/img/default_profile.png. A square PNG of 128x128 pixels works well: it’s shown at 64x64, and the extra pixels keep it sharp on high-resolution screens. The example code includes one.
Then use it wherever users are created: in register_post_view, in db/create_user.py, and in the example in UserIn:
new_user = User(first_name=first_name, last_name=last_name, email=email, username=email,
profile_image="/static/img/default_profile.png", is_active=False, # UPDATED
hashed_password=get_password_hash_api(password))For existing users in your database, update the profile_image column, for example with sqlite3:
UPDATE user SET profile_image = '/static/img/default_profile.png' WHERE profile_image = '/static/img/profile.jpg';Showing profile images#
The blog post template can now show the author’s image next to their name:
<span class="meta">Posted on {{ context.post.created_date.strftime('%d %B %Y') }}{% if context.post.blogpost_author %}
by <img src="{{ context.post.blogpost_author.profile_image }}" alt="" width="32" height="32" class="img-circle">
{{ context.post.blogpost_author.first_name }} {{ context.post.blogpost_author.last_name }}{% endif %}</span>And next to each comment:
<h6>{% if comment.comment_author %}<img src="{{ comment.comment_author.profile_image }}" alt="" width="32" height="32" class="img-circle"> {% endif %}Commented on {{ comment.created_date.strftime('%d %B %Y') }}{% if comment.comment_author %}
by {{ comment.comment_author.first_name }} {{ comment.comment_author.last_name }}{% endif %}</h6>img-circle is a Bootstrap 3 class that makes the image round.
Updating details#
Users can change their name and profile image, but not everything: their email address is their username, and flags like is_author are for administrators. Add a schema with just what users can change:
# What users can change about themselves
class UserProfileIn(SQLModel):
first_name: str = Field(min_length=1)
last_name: str = Field(min_length=1)
profile_image: strAnd an API to update a user with it. Import UserProfileIn:
@router.put('/auth/user/{id}/profile', status_code=status.HTTP_200_OK)
def update_user_profile_api(id: uuid.UUID, data: UserProfileIn, session: Session = Depends(get_session_db)) -> UserOut:
user = session.get(User, id)
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No user found with id {id}.")
user.sqlmodel_update(data.model_dump())
session.add(user)
session.commit()
session.refresh(user)
return userUploading an image#
Uploaded profile images need the same care as blog cover images: checking they’re really images, cropping them to size, and saving them under a new name. Rather than copy that code, generalise the helper in web/images.py to take a size, and add one function for each kind of image:
import io
import uuid
from pathlib import Path
from fastapi import HTTPException, UploadFile, status
from PIL import Image, ImageOps, UnidentifiedImageError
from config.settings import settings
COVER_IMAGE_SIZE = (1900, 600)
PROFILE_IMAGE_SIZE = (128, 128) # shown at 64x64, sharp on high-resolution screens
MAX_UPLOAD_BYTES = 10 * 1024 * 1024 # 10 MB
def save_image(upload: UploadFile, size: tuple[int, int]) -> str:
"""Validate, crop/resize and save an uploaded image. Returns its URL path."""
data = upload.file.read(MAX_UPLOAD_BYTES + 1)
if len(data) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=status.HTTP_413_CONTENT_TOO_LARGE, detail="Image is too large.")
try:
image = Image.open(io.BytesIO(data))
image.load()
except (UnidentifiedImageError, OSError):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Upload is not a valid image.")
# Respect the camera's orientation, then crop to fill the size without distortion
image = ImageOps.exif_transpose(image)
image = ImageOps.fit(image.convert("RGB"), size)
# Never trust the uploaded file name: generate our own
filename = f"{uuid.uuid4()}.jpg"
upload_dir = Path(settings.CONF_IMAGE_UPLOADS_FILE_PATH)
upload_dir.mkdir(parents=True, exist_ok=True)
image.save(upload_dir / filename, "JPEG", quality=85)
return settings.CONF_IMAGE_UPLOADS_CONTEXT_PATH + filename
def save_cover_image(upload: UploadFile) -> str:
return save_image(upload, COVER_IMAGE_SIZE)
def save_profile_image(upload: UploadFile) -> str:
return save_image(upload, PROFILE_IMAGE_SIZE)save_cover_image works exactly as before, so the blog views don’t change.
Now the POST view for the details form:
@router.post('/profile', response_class=HTMLResponse)
def profile_update_view(*,
request: Request,
first_name: str = Form(...),
last_name: str = Form(...),
profile_image: UploadFile | None = File(None),
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)
profile_image_path = current_user.profile_image
if profile_image and profile_image.filename:
profile_image_path = save_profile_image(profile_image)
user_updates = UserProfileIn(first_name=first_name, last_name=last_name, profile_image=profile_image_path)
# Always the logged-in user: never an id sent by the browser
update_user_profile_api(id=current_user.id, data=user_updates, session=session)
return profile_page(request, current_user, message="Your details have been updated.")The form has no id field. The view always updates the logged-in user, current_user.id.
An earlier version of this guide sent the user’s id in a read-only form field, and updated whichever user it named. Any logged-in user could have changed anyone’s name and image. As with comments, identity comes from the login cookie, never from the form.
If no new image is chosen, the user keeps their current one.