簡體   English   中英

在URLConf中定義嵌套命名空間,用於反轉Django URL - 有沒有人有一個有說服力的例子?

[英]Defining nested namespaces in a URLConf, for reversing Django URLs — does anyone have a cogent example?

我一直試圖弄清楚如何在Django URLConf中定義嵌套的URL命名空間( look:like:this )。

在此之前,我想出了如何做一個基本的URL命名空間,並提出了這個簡單的示例代碼片段 ,其中包含了您可能放在urls.py文件中的內容:

from django.conf.urls import patterns, include, url

# you can only define a namespace for urls when calling include():

app_patterns = patterns('',
    url(r'^(?P<pk>[\w\-]+)/$', 'yourapp.views.your_view_function',
        name="your-view"),
)

urlpatterns = patterns('',
    url(r'^view-function/', include(app_patterns,
        namespace='yournamespace', app_name='yourapp')),
)

"""

    You can now use the namespace when you refer to the view, e.g. a call
    to `reverse()`:

    # yourapp/models.py

    from django.core.urlresolvers import reverse

    # ...

    class MyModel(models.Model):

        def get_absolute_url(self):
            return reverse('signalqueue:exception-log-entry', kwargs=dict(pk=self.pk))

"""

... w / r / t Django文檔的推導,在這種情況下,根本沒有幫助。 雖然Django的doc在所有其他方面都很棒,但這是規則的一個例外,關於定義嵌套URL命名空間的信息甚至更少。

我想,如果有人擁有或知道一個直接有說服力和/或不言自明的URLconf定義嵌套命名空間的例子,我可能會問他們可以分享這些嘗試。

具體來說,我很好奇視圖前綴的嵌套部分:需要它們安裝Django應用程序嗎?

†)對於好奇,這是一個(可能有點難以理解)的例子: http//imgur.com/NDn9H 我試圖將底部以紅色和綠色打印的URL命名為testapp:views:<viewname>而不僅僅是testapp:<viewname>

它的工作非常直觀。 include URL配置已經又命名空間include將導致嵌套的命名空間。

## urls.py
nested2 = patterns('',
   url(r'^index/$', 'index', name='index'),
)

nested1 = patterns('',
   url(r'^nested2/', include(nested2, namespace="nested2"),
   url(r'^index/$', 'index', name='index'),
)   

urlpatterns = patterns('',
   (r'^nested1/', include(nested1, namespace="nested1"),
)

reverse('nested1:nested2:index') # should output /nested1/nested2/index/
reverse('nested1:index') # should output /nested1/index/

這是保持網址組織的好方法。 我想我能給出的最好建議是記住include可以直接采用patterns對象(如我的例子中所示),它允許您使用單個urls.py並將視圖拆分為有用的命名空間,而無需創建多個url文件。

雖然Yuji的答案是正確的,但請注意django.conf.urls.patterns不再存在(因為Django 1.10)而使用普通列表。

同樣的例子urls.py應該是這樣的:

from django.conf.urls import include, url

nested2 = [
   url(r'^index/$', 'index', name='index'),
]   

nested1 = [
   url(r'^nested2/', include(nested2, namespace='nested2'),
   url(r'^index/$', 'index', name='index'),
]   

urlpatterns = [
   url(r'^nested1/', include(nested1, namespace='nested1'),
]   

仍然使用像:

reverse('nested1:nested2:index') # should output /nested1/nested2/index/
reverse('nested1:index') # should output /nested1/index/


更新: Django 2.0引入了兩個相關的更改。 首先, urls()函數現在位於django.urls ,因此上面urls.py示例的第一行將是:

from django.urls import include, url

其次,它引入了path()函數作為不需要正則表達式的路徑的更簡單的替代方法。 使用它,示例urls.py將是這樣的:

from django.urls import include, path

nested2 = [
   path('index/', 'index', name='index'),
]   

nested1 = [
   path('nested2/', include(nested2, namespace='nested2'),
   path('index/', 'index', name='index'),
]   

urlpatterns = [
   path('nested1/', include(nested1, namespace='nested1'),
]

Python Django - 包含的 URLconf ' <module '{spp}.urls' from {path} does not appear to have any patterns in it< div><div id="text_translate"><p> 我正在閱讀 Eric Matthes 撰寫的 Python Crash Course 中的第 18 章,這是一個關於如何使用 Django 創建 web 應用程序的教程。 目前我正在映射 URL,編寫視圖,編寫模板,然后嘗試在我的系統上部署應用程序,以便我可以看到我創建的主頁。</p><p> 以下是相關文件/代碼:</p><p> urls.py-learning_log</p><pre> from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls')) ]</pre><p> urls.py-learning_logs</p><pre> """Defines URL patterns for learning_logs.""" from django.urls import path from. import views app_name = 'learning_logs' url_patterns = [ # Home page path('', views.index, name='index'), ]</pre><p> 視圖.py</p><pre> from django.shortcuts import render def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html')</pre><p> 索引.html</p><pre> &lt;p&gt;Learning Log&lt;/p&gt; &lt;p&gt;Learning Log helps you to keep track of your learning, for any topic you're learning about.&lt;/p&gt;</pre><p> 當我嘗試使用 Powershell 為 Windows 的項目的虛擬環境中使用runserver命令創建服務器時,這是我得到的錯誤:</p><pre> (ll_env) PS C:\Users\Samie\Desktop\python_work\learning_log&gt; python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Samie\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Samie\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 408, in check messages.extend(check_resolver(pattern)) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '&lt;module 'learning_logs.urls' from 'C:\\Users\\Samie\\Desktop\\python_work\\learning_log\\learning_logs\\urls.py'&gt;' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.</pre><p> 作為一個超級綠色的 Python/Django 用戶,這對我來說已經消化了很多。 任何人都可以在這里看到我哪里出錯了嗎? 我知道我為這個項目安裝的 Django 版本比本書出版時(2019 年)新,這可能是問題嗎? 感謝您提供的任何幫助!</p></div></module>

[英]Python Django - the included URLconf '<module '{spp}.urls' from {path} does not appear to have any patterns in it

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 django.core.exceptions.ImproperlyConfigured:包含的 URLconf 'api.urls' 似乎沒有任何模式 Python Django - 包含的 URLconf ' <module '{spp}.urls' from {path} does not appear to have any patterns in it< div><div id="text_translate"><p> 我正在閱讀 Eric Matthes 撰寫的 Python Crash Course 中的第 18 章,這是一個關於如何使用 Django 創建 web 應用程序的教程。 目前我正在映射 URL,編寫視圖,編寫模板,然后嘗試在我的系統上部署應用程序,以便我可以看到我創建的主頁。</p><p> 以下是相關文件/代碼:</p><p> urls.py-learning_log</p><pre> from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls')) ]</pre><p> urls.py-learning_logs</p><pre> """Defines URL patterns for learning_logs.""" from django.urls import path from. import views app_name = 'learning_logs' url_patterns = [ # Home page path('', views.index, name='index'), ]</pre><p> 視圖.py</p><pre> from django.shortcuts import render def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html')</pre><p> 索引.html</p><pre> &lt;p&gt;Learning Log&lt;/p&gt; &lt;p&gt;Learning Log helps you to keep track of your learning, for any topic you're learning about.&lt;/p&gt;</pre><p> 當我嘗試使用 Powershell 為 Windows 的項目的虛擬環境中使用runserver命令創建服務器時,這是我得到的錯誤:</p><pre> (ll_env) PS C:\Users\Samie\Desktop\python_work\learning_log&gt; python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Samie\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Samie\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 408, in check messages.extend(check_resolver(pattern)) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '&lt;module 'learning_logs.urls' from 'C:\\Users\\Samie\\Desktop\\python_work\\learning_log\\learning_logs\\urls.py'&gt;' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.</pre><p> 作為一個超級綠色的 Python/Django 用戶,這對我來說已經消化了很多。 任何人都可以在這里看到我哪里出錯了嗎? 我知道我為這個項目安裝的 Django 版本比本書出版時(2019 年)新,這可能是問題嗎? 感謝您提供的任何幫助!</p></div></module> django.core.exceptions.ImproperlyConfigured:包含的 URLconf“notes.urls”似乎沒有任何模式 包含的 URLconf 'appName.urls' 中似乎沒有任何模式 包含的 URLconf 'myapp.urls' 中似乎沒有任何模式 Django 說配置不當:包含的 URLconf 中似乎沒有任何模式 包含的 URLconf 中似乎沒有任何模式。 錯誤Django Django1.11-URLconf似乎沒有任何模式 Django錯誤“包含的URLconf中似乎沒有任何模式” 配置不當:包含的URLconf“buttonpython.urls”似乎沒有任何模式
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM