【问题标题】:How to use namespace in django + Problems after this如何在 django 中使用命名空间 + 之后的问题
【发布时间】:2021-09-01 00:19:19
【问题描述】:

我查看了官方的 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.

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

第二个问题:

谢谢!连接良好 &lt;a href="{% url 'music:home-page' %}"&gt;(to app_name = 音乐)

但是,当我从音乐应用程序调用表单并加载要生成的 url 时,出现错误。其他 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'),
]

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

【问题讨论】:

  • 你需要在math_note.urls中指定一个app_name

标签: python django django-urls


【解决方案1】:

include 接受的 namespace kwarg 是 instance 命名空间 即应用程序命名空间的实例,如果没有 应用程序命名空间,则不能拥有实例命名空间正如错误指定的那样,您可以通过在包含的模块中指定 app_name 或将包含模式和应用程序命名空间的 2 元组传递给 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'))
]

【讨论】:

【解决方案2】:

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

【讨论】:

    【解决方案3】:

    views.py

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

    使用name 而不是namespace

    【讨论】:

      【解决方案4】:

      app_name 在应用程序url 中将作为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'),
          ]
      

      【讨论】:

        【解决方案5】:

        第二个问题的答案。

        我已经设置了导航栏,所以我看不到确切的错误代码内容。删除导航栏的时候,看到了准确的错误内容,错误的原因是返回链接。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-05
          • 2010-12-27
          • 1970-01-01
          相关资源
          最近更新 更多