From c57ac6b631d50b47a8dddba6b98d3c624175fc52 Mon Sep 17 00:00:00 2001 From: Josh Thomas Date: Tue, 13 Feb 2024 16:08:28 -0600 Subject: [PATCH] adjust favicon view to find file using staticfiles (#22) --- CHANGELOG.md | 1 + .../{{ module_name }}/core/views.py | 20 +++++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1ba155b..2207bce0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - Actually use Copier `python_version` input for `ruff` Python target version. - Add some `ruff` per-file ignores for tests. - Add rules for `pyupgrade` to `ruff` config. +- Favicon view in `core.views` now uses `django.contrib.staticfiles` to find the favicon file. ### Removed diff --git a/src/django_twc_project/{{ module_name }}/core/views.py b/src/django_twc_project/{{ module_name }}/core/views.py index 0c84b33a..f90c3874 100644 --- a/src/django_twc_project/{{ module_name }}/core/views.py +++ b/src/django_twc_project/{{ module_name }}/core/views.py @@ -1,10 +1,14 @@ from __future__ import annotations -from django.conf import settings +from pathlib import Path + from django.contrib.auth.decorators import login_required +from django.contrib.staticfiles import finders from django.http import FileResponse from django.http import HttpRequest from django.http import HttpResponse +from django.http import HttpResponseNotFound +from django.shortcuts import redirect from django.shortcuts import render from django.utils import timezone from django.views.decorators.cache import cache_control @@ -45,10 +49,18 @@ def security_txt(request: HttpRequest) -> HttpResponse: @require_GET @cache_control(max_age=60 * 60 * 24, immutable=True, public=True) # one day -def favicon(request: HttpRequest) -> FileResponse: +def favicon(request: HttpRequest) -> HttpResponse | FileResponse: name = request.path.lstrip("/") - file = (settings.BASE_DIR / "static" / "public" / name).open("rb") - return FileResponse(file) + path = finders.find(name) + if path: + file = Path(path).open("rb") + response = FileResponse(file) + else: + if name == "favicon.ico": + response = HttpResponseNotFound() + else: + response = redirect("favicon.ico") + return response @require_GET