Skip to content

Commit

Permalink
adjust favicon view to find file using staticfiles (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuadavidthomas authored Feb 13, 2024
1 parent cdd4637 commit c57ac6b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 16 additions & 4 deletions src/django_twc_project/{{ module_name }}/core/views.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit c57ac6b

Please sign in to comment.