NoReverseMatch: Reverse for ‘…’ not found. ‘…’ is not a valid view function or pattern name – for path include name

  Kiến thức lập trình

I have this setup:

# Django Project: core/urls.py
def redirect_index(request):
    return redirect(reverse('account'), permanent=False)

urlpatterns = [
    path('', redirect_index, name='index'),
    path('account/', include('identity.urls'), name='account'),
]
# Django App: identity/urls.py
app_name = 'identity'

def redirect_index(request):
    return redirect(reverse('identity:login'), permanent=False)

def view_login(request):
    context = {"test_context": 'This is a test context'}
    return render(request, "common/base.html", context)

urlpatterns = [
    path('', redirect_index, name='index'),
    path('login', view_login, name='login'),
]

When I visit http://localhost:8000/, I get this error:

NoReverseMatch at /
Reverse for 'account' not found. 'account' is not a valid view function or pattern name.

What I want is this:

If user goes to /, it should redirect to /account/, and from there redirect to /account/login. I know there are 2 redirects, but I’d like to have them separate so that I can set each one separately. But I get the above error. It looks like when there is an include, the name cannot be reversed.

Of course, when I use reverse('identity:index') or reverse('identity:login') instead of reverse('account') in core/urls.py, it works.

Is there no way I can do it the way I described earlier?

LEAVE A COMMENT