django.urls.exceptions.NoReverseMatch: ... is not a registered namespace

Hi there!

I have a Django project with a middleware which sets request.urlconf depending on the host header. Here’s the middleware:

class VhostMiddleware:
def __init__(self, get_response):
    self.get_response = get_response
    self.vhosts = {"hosta.example.com": "app_a.urls", "host_b.example.com": "app_b.urls"}

def __call__(self, request):
    urlconf = self.vhosts.get(request.get_host())
    request.urlconf = urlconf
    response = self.get_response(request)
    return response

For app_a I have a set of urls:

app_name = "app_a"
urlpatterns = [
    path("feedback/", FeedbackCreateView.as_view(), name="feedback_create"),
    path("feedback-thanks/", feedback_thanks, name="feedback_thanks"),
]

The template for feedback/ has a form which calls the view:

<form action="{% url "app_a:feedback_create" %}" method="post">

Now the problem is that the template does not like “app_a:feedback_create” and raises:

django.urls.exceptions.NoReverseMatch: … is not a registered namespace

When instead I do:

<form action="{% url "feedback_create" %}" method="post">

everything works great. Could be because the middleware loads just one urlconf and the namespace becomes irrelevat?

Thank you!

Have you tried it without the namespace? It’s looking for one, and the app name is not a namespace. Typically you would define a namespace in the root urls.py in a path that includes your app_a.urls. Since this IS your root urls.py because of the middleware, the namespace isn’t defined, or needed.

Yeah, I came to the same conclusion and in the end I solved calling url without the namespace.