如何更改根URL配置,以便为用户URL使用名称空间 [英] How to change root URL configuration in order to use a namespace for the user URLs
问题描述
整个网址:
from user import urls as user_urls
app_name='user'
urlpatterns = [
re_path(r'^user/',include(user_urls)),
]
自 admin 应用以来,还定义了名为 login
和 logout的URL模式。
在 django / contrib / admin / sites.py
中。我需要Django指向 user 应用。
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.
它仍然指向 registration / login.html
(即管理应用)。我尝试过命名空间,但在Django 2.0中已将其删除。
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:
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'
),
]
推荐答案
要在django 2中按名称空间访问URL,您需要将 app_name
属性移至 user / urls.py
将变为;
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'
),
]
URL在 users.urls
中定义的应用程序命名空间为 user
。
The URLs defined in users.urls
will have an application namespace of user
.
或者,您可以通过在同一文件中对URL进行命名空间;
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)),
]
关于此的文档可以在这里找到; https://docs.djangoproject .com / zh-CN / 2.0 / topics / http / urls /#url-namespaces-and-included-urlconfs
The docs on this can be found here; https://docs.djangoproject.com/en/2.0/topics/http/urls/#url-namespaces-and-included-urlconfs
这篇关于如何更改根URL配置,以便为用户URL使用名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!