Randy Tang
Randy Tang

Reputation: 4363

Django: namespace isn't unique

In Django 1, I used to have the following URL mappings:

...
url(r'^main/', include('main.urls', namespace='main')),
url(r'.*', include('main.urls'))

The r'.*' mapping is always at the last line to take care of all kinds of URLs not mapped.

In Django 2, the following mappings are used instead:

path('main/', include('main.urls', namespace='main')),
re_path('.*', include('main.urls')),

Although it also works, yet Django complains:

?: (urls.W005) URL namespace 'main' isn't unique. You may not be able to reverse all URLs in this namespace

Giving the second mapping another namespace is not working. Any solutions?

Upvotes: 0

Views: 1153

Answers (2)

Shift 'n Tab
Shift 'n Tab

Reputation: 9443

In that case you can use django.views.generic.base.RedirectView to simply redirect to the said url without importing it twice.

urlpatterns = [
    path('main', include('main.urls')),
    re_path('.*', RedirectView.as_view(url='main/your_default_url_in_main_url'), name='main'),
]

Try to remove the trailing slash of 'main/' and change to 'main'.

Note: If your main.urls looks like this

urlpatterns = [
    path('/whatever1', view1), 
    path('/whatever2', view2), 
]

You have to pick where to redirect the default view by supplying RedirectView.as_view(url='main/whatever1') to redirect to view1 as default. use 'main/whatever2' to redirect to view2 as default

reference: RedirectView

Upvotes: 0

Kevin L.
Kevin L.

Reputation: 1471

try writing a view to redirect to main/ and then include the view in your urls:

re_path('.*', views.redirect_view)

Upvotes: 1

Related Questions