LoginSignup
1
0

More than 1 year has passed since last update.

Djangoのurls.pyの中でreverse関数でエラーが起きてしまったときの対処法

Last updated at Posted at 2021-03-10

いつかの昔のメモが見つかりました。ಠ⁠︵⁠ಠ

###環境

Python 3.8.7
Django==2.2

###エラー内容

urls.pyの中で、次に遷移するページのURLをviewのクラス変数に渡したいなと思ったので、
views.pyの中で、

class HogeView(TemplateView):
    (略)
    next_url=''

みたいに、ビューにURLを保持する変数をを定義。
そして、urls.pyで、

from django.urls import reverse
import .views import HogeView
(略)
HogeView.as_view(next_url=reverse(’逆引き用文字列’))

としたら、、、うまく読み込んでくれなかった。
エラー内容は、

django.core.exceptions.ImproperlyConfigured: The included URLconf 'config.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

と出た。

###解決策

エラー内容をググってみると。
URLConfが読み込まれるタイミングの問題らしい。
→urls.py内で逆引き用文字列nameを定義すると同時に、同じurls.pyでそのnameを参照している。

そこで、urls.pyを読み込んだ後にnameからURLを取得してくれる(遅延評価)らしいreverse_lazyを使ってみた。

from django.urls import reverse_lazy
import .views import HogeView
(略)
HogeView.as_view(next_url=reverse_lazy(’逆引き用文字列’))

そしたらうまくいっただけの話。

間違いなどあればご指摘お願い申し上げます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0