Djangoで勉強していて起きたエラーとその解決方法を備忘録的な感じでまとめてみました。
発生したエラーのうち大半がしょーもないミスだったりするんですよね~
初歩的なミスほどなかなか気づけずに時間を無駄にしたり……
開発環境
- OS: Windows10 home 64bit
- フレームワーク: Django 3.1.2
- 言語: python 3.9
手を加えるファイル
fetch_apps/ ├ templates/ │ └ fetch_apps/ │ ├ index.html │ └ index2.html ├ urls.py └ views.py
※変更を加えるファイルのみ表示しています。
実際はmanage.py等、必要なファイルはありますが手を加えないため上には記載しません。
[NoReverseMatch at ~]エラーを起こしてみる
<!-- fetch_apps/templates/fetch_apps/index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>fetch app</title> </head> <body> <h1>index</h1> <a href="{% url 'fetch_apps:index2' %}"> index2 </a> </body> </html>
想定では上のindex画面は正常に開かれるはずです。
<!-- fetch_apps/templates/fetch_apps/index2.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>fetch app</title> </head> <body> <h1>index2</h1> <a href="{% url 'index' %}"> <!-- 1 --> index </a> </body> </html>
- 1: 今回はurls内でapp_nameを設定しているのでこの書き方をすると本題に書いたエラーが発生します。
# fetch_apps/urls.py from django.urls import path from fetch_apps import views app_name = 'fetch_apps' # 2 urlpatterns = [ path('', views.index, name='index'), path('index2', views.index2, name='index2'), ]
- 2: ここでapp_nameを設定しています。
# fetch_apps/views.py from django.shortcuts import render def index(request): return render(request, 'fetch_apps/index.html') def index2(request): return render(request, 'fetch_apps/index2.html')
これでpython manage.py runserverを実行すると以下のエラーが発生します。

解決方法
上の画像にヒントが表示されていますが、index2.htmlを下のように直せば解決できます。
<!-- fetch_apps/templates/fetch_apps/index2.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>fetch app</title> </head> <body> <h1>index2</h1> <a href="{% url 'fetch_apps:index' %}"> <!-- 3 --> index </a> </body> </html>
- 3: urls.pyで書いたapp_nameとコロンを追加することで解決
おまけ
上記以外にNoReverseMatch at ~のエラーが出る原因を見つけたので備忘録として残しておきます。
上記のファイルをそのままにfetch_apps/urls.pyのnameを下のように変更
from django.urls import path from fetch_apps import views app_name = 'fetch_apps' urlpatterns = [ path('', views.index, name='no'), # html側のurlと値が不一致 path('index2', views.index2, name='index2'), ]
すると同じエラーが発生しました。
最後に
今回は見落としがちな(私だけ……?)ミスとその解決方法をまとめてみました。
この記事が何かの役に立てば幸いです。
ここまで読んでくれてありがとう!!
コメント