如何更改根URL配置,以便为用户URL使用名称空间

时间:2018-11-07 15:26:19

标签: django django-authentication

全站点网址:

from user import urls as user_urls
app_name='user'

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

admin 应用以来,还在login中定义了名为logoutdjango/contrib/admin/sites.py的URL模式。我需要Django指向 user 应用。

它仍指向registration/login.html(即管理应用)。我尝试过命名空间,但在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 个答案:

答案 0 :(得分:1)

要在django 2中按名称空间访问URL,您需要移动app_name属性,以使user/urls.py成为;

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

users.urls中定义的URL的应用程序命名空间为user

或者,您可以通过执行以下操作在同一文件中命名URL:

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

有关此文档,请参见此处; https://docs.djangoproject.com/en/2.0/topics/http/urls/#url-namespaces-and-included-urlconfs