JUNのブログ

JUNのブログ

活動記録や技術メモ

Djangoの Internal Server Error: /favicon.ico を直す

ローカル環境上のDjangopython manage.py runserver したら,ログにこんなメッセージが

[22/Jul/2019 02:44:16] "GET / HTTP/1.1" 200 5895
Internal Server Error: /favicon.ico
Traceback (most recent call last):
  File "/home/jun/.local/share/virtualenvs/TobaExPy-uha27gFP/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/jun/.local/share/virtualenvs/TobaExPy-uha27gFP/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/jun/.local/share/virtualenvs/TobaExPy-uha27gFP/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/jun/Desktop/work_space/TobaExPy/Toba/views.py", line 30, in detail
    place = Place.objects.get(place_id=place_id)
  File "/home/jun/.local/share/virtualenvs/TobaExPy-uha27gFP/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/jun/.local/share/virtualenvs/TobaExPy-uha27gFP/lib/python3.6/site-packages/django/db/models/query.py", line 408, in get
    self.model._meta.object_name
Toba.models.Place.DoesNotExist: Place matching query does not exist.
[22/Jul/2019 02:44:16] "GET /favicon.ico HTTP/1.1" 500 78881

大事なのは Internal Server Error: /favicon.icoGET /favicon.ico HTTP/1.1" 500 78881 の部分.

ようは favicon.ico が無いというだけなのだが,これを直すのが少し時間がかかったのでここに書いておく.

プロジェクトのディレクトリ構造(修正後)

├── app
│   ├── __init__.py
│   ├── admin.py
│   ├── apis.py
│   ├── apps.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── config
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
├── static
│   ├── css
│   │   └── index.css
│   └── img
│       └── favicon.ico
└── templates
    └── app
        ├── base.html
        └── index.html

直し方

/static/img/favicon.ico を設置.

/config/settings.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

を追記.

/templates/app/base.html の <head> 内に

<link rel="icon" href="{% static 'img/favicon.ico' %}">

を書き込む.

各種ファイル名等はプロジェクトの構成によって柔軟に対応してもらえればいいと思います.