Search code examples
pythondjangoimporturl-pattern

Why can't I import urlpatterns from urls.py?


I am trying to create a simple Django view that will render a list of links to all of the other views in my app.

my plan was to simply import my list of urlpatterns from urls.py like this

from urls import urlpatterns

and then generate a list of names like this

def get(self, request, *args, **kwargs):
    context={"urlnames":[]}
    for up in urlpatterns:
        context["urlnames"].append(up.name)
    return render_to_response('api_list.html', context)

and then render them like this

{% for urlname in urlnames %}
<div>
  <a href='{% url urlname %}' > {{urlname}} </a>
</div>
{% endfor %}

But python cant import urlpatterns at import time. If I try to do it later, by putting the import statement in my get request, then it works fine, but why doesn't it work at import time?


Solution

  • Circular import is happening! Import module as import urls and get urlpatterns like this:

    def get(self, request, *args, **kwargs):
        context={"urlnames":[]}
        for up in urls.urlpatterns:
            context["urlnames"].append(up.name)
        return render_to_response('api_list.html', context)