tklodd
tklodd

Reputation: 1079

Django: cannot import name 'url_patterns'

I have a weird edge-case where I need to use the data stored in urls.py within a view, but since the urls.py file imports the view, I am getting a circular import error when I try to import the url data into the view.

cannot import name 'url_patterns'

Does Django have any way of grabbing all the url patterns within a view that could circumvent this error? The fact that the reverse() function exists indicates that it might.

Upvotes: 0

Views: 112

Answers (2)

tklodd
tklodd

Reputation: 1079

Found an answer:

from django.urls import get_resolver
url_patterns = set(v[1] for k,v in get_resolver(None).reverse_dict.items())

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477190

You can solve this typically (well it depends a bit), by importing the urls in your view(s) locally. Like:

# urls.py

import someapp.views

url_patterns = [
    url('some_url/', someapp.views.some_view),
]

and then import the urls in the views like:

# views.py

def some_view(request):
    from someapp.urls import url_patterns
    # ...
    # do something with urlpatterns
    # return response
    pass

We here thus postpone the importing of the urls.py in the views, until the view function is actually called. By that time both the views.py and urls.py are (usually) already loaded. You can however not call the view in the views.py directly, since then the import is done before the urls.py is loaded.

Note that usually you do not have to import url_patterns, and you can use reverse(..) etc. to obtain a URL that corresponds to a view function (even passing parameters into a dictionary, etc.). So I really advice to look for Django tooling to handle URLs.

Upvotes: 3

Related Questions