如何在 django 中使用命名空间 + 在此之后的问题

How to use namespace in django + Problems after this

看了Django官方文档(https://docs.djangoproject.com/en/3.2/topics/http/urls/#reversing-namespaced-urls)和错误码,写下了以下内容。如何编写名称空间才能工作?

views.py:

from django.urls import path, include

app_name = 'home'
urlpatterns = [
    path('math/', include('math_note.urls', namespace='math-note'))
]

模板:

<a href="{% url 'home:math-note' %}">math note</a>

运行 运行服务器时出错: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

问题: 如何使用命名空间功能?

第二个问题:

谢谢!通过良好连接 <a href="{% url 'music:home-page' %}">(到 app_name = 音乐)

但是当我从音乐应用程序调用表单并加载 url 以生成时,出现错误。其他网址没有任何问题,只有这个。

Reverse for 'home-page' not found. 'home-page' is not a valid view function or pattern name.

#music/urls.py

from django.urls import path
from . import views

app_name = 'music'
urlpatterns = [
    path('', views.music_home_page, name='home-page'),
    path('new/', views.new_song, name='new'),
    path('music_player/<int:id>/', views.music_player, name='music-player'),
]

问题: 我解决了前面的问题并得到了以下问题。这是什么原因和解决方法?

只需从路径中删除命名空间。 包括 url 不需要有命名空间。在你的数学笔记上有你的命名空间就足够了。

views.py

from django.urls import path, include

app_name = 'home'
urlpatterns = [
    path('math/', include('math_note.urls', name='math-note'))
]

使用name代替namespace

include 接受的 namespace kwarg 是一个 实例命名空间 即应用程序命名空间的实例,如果没有 application namespace 错误指定您通过在包含的模块中指定 app_name 或将包含模式和应用程序命名空间的二元组传递给 include.

因此你需要修改math_note.urls并添加一个app_name变量:

app_name = 'math_note'

urlpatterns = [
    ...
]

保持您的其他网址(可能在 home.urls 中?)原样:

from django.urls import path, include

app_name = 'home'
urlpatterns = [
    path('math/', include('math_note.urls', namespace='math-note'))
]
应用程序 url 中的

app_name 将作为 namespace 工作。只需从根项目目录中的 include 中删除 namespace

你的 urlpatterns 应该是这样的:

urlpatterns = [
    path('math/', include('math_note.urls'))
]

并在您的应用程序 urls 中定义 app_name='home'。 类似于:

`app_name='home'`

urlpatterns = [
        path('list/', <your view>, name='app-list'),
    ]

第二个问题的答案。

我已经设置了导航栏,所以看不到确切的错误代码内容。当我删除导航栏时,我看到了确切的错误内容,错误的原因是 return link.