A real example of URL Namespace

前端 未结 3 1409
囚心锁ツ
囚心锁ツ 2020-12-07 15:47

I am studying the Django documentation, but I encountered a part that I cannot understand: what is a real example of how use to use a namespace in a real problem. I know the

3条回答
  •  暖寄归人
    2020-12-07 16:20

    Consider you are using a url pattern as below
    url(r'^login/',include('app_name', name='login'))

    Also Consider you are using a third-party app like Django-RestFramework. When you use the app, you have to declare the following line in URLs conf file of the project.

    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    

    Now if you check the code of rest-framework, you will find the below code in urls.py file

    urlpatterns = [
        url(r'^login/$', login, login_kwargs, name='login'),
        url(r'^logout/$', logout, name='logout'),
    ]
    

    We have used 'login' name for a URL pattern in our project and the same name is being used by Django-rest-framework for one of their URL patterns. When you use reverse('login'), Django will get confused.
    To resolve these kinds of issues, we use namespace.

    @register.simple_tag
    def optional_docs_login(request):
        """
        Include a login snippet if REST framework's login view is in the URLconf.
        """
        try:
            login_url = reverse('rest_framework:login')
        except NoReverseMatch:
            return 'log in'
    

    URL names of a namespace will never collide with other namespaces.
    A namespaced URL pattern can be reversed using
    reverse('namespace:url_name')

提交回复
热议问题