Search code examples
djangodjango-authentication

How to change root URL configuration in order to use a namespace for the user URLs


Site-Wide URL:

from user import urls as user_urls
app_name='user'

urlpatterns = [
    re_path(r'^user/',include(user_urls)),    
]

Since the admin app, also defines URL patterns named login and logout in django/contrib/admin/sites.py. I need Django pointing to user app.

It's still pointing towards registration/login.html (i.e admin app). I tried namespacing but its been removed in Django 2.0.

user/urls.py :

urlpatterns = [
    path(r'',RedirectView.as_view()),

    re_path(
        r'^login/$',auth_views.LoginView.as_view(template_name='user/login.html'), 
        name='login'
    ),

    re_path(
        r'^logout/$',auth_views.LogoutView.as_view(template_name='user/logged_out.html') 
, 
        {
            'extra_context':{'form':AuthenticationForm }
        }, name='logout'
    ),
]

Solution

  • In order to access the URLs by namespace in django 2 you need to move you app_name attribute so user/urls.py would become;

    app_name = 'user'
    urlpatterns = [
        path(r'', RedirectView.as_view()),
    
        re_path(
            r'^login/$',auth_views.LoginView.as_view(), 
            {'template_name':'user/login.html'},
            name='login'
        ),
    
        re_path(
            r'^logout/$',auth_views.LogoutView.as_view(), 
            {
                'template_name':'user/logged_out.html',
                'extra_context':{'form':AuthenticationForm }
            },
            name='logout'
        ),
    ]
    

    The URLs defined in users.urls will have an application namespace of user.

    Alternatively you could namespace URLs in the same file by doing;

    user_patterns = ([
        path(r'', RedirectView.as_view()),
    
        re_path(
            r'^login/$',auth_views.LoginView.as_view(), 
            {'template_name':'user/login.html'},
            name='login'
        ),
    
        re_path(
            r'^logout/$',auth_views.LogoutView.as_view(), 
            {
                'template_name':'user/logged_out.html',
                'extra_context':{'form':AuthenticationForm }
            },
            name='logout'
        ),
    ], 'user')
    
    urlpatterns = [
        re_path(r'^user/', include(user_patterns)),    
    ]
    

    The docs on this can be found here; https://docs.djangoproject.com/en/2.0/topics/http/urls/#url-namespaces-and-included-urlconfs