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

跟風遠走 提交于 2019-12-14 03:08:18

问题


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'
    ),
]

回答1:


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



来源:https://stackoverflow.com/questions/53192533/how-to-change-root-url-configuration-in-order-to-use-a-namespace-for-the-user-ur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!