简体   繁体   English

在URLConf中定义嵌套命名空间,用于反转Django URL - 有没有人有一个有说服力的例子?

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

I have been trying to to figure out how to define a nested URL namespace (which look:like:this ) in a Django URLConf. 我一直试图弄清楚如何在Django URLConf中定义嵌套的URL命名空间( look:like:this )。

Before this, I figured out how to do a basic URL namespace and came up with this simple example snippet , containing what you might put in a urls.py file: 在此之前,我想出了如何做一个基本的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 the deduction of which the Django documentation was, in this case, not at all helpful. ... w / r / t Django文档的推导,在这种情况下,根本没有帮助。 While Django's doc is fantastic in all other respects, and this is an exception to the rule, there is even less information about defining nested URL namespaces. 虽然Django的doc在所有其他方面都很棒,但这是规则的一个例外,关于定义嵌套URL命名空间的信息甚至更少。

Instead of posting my spaghettified attempts† to figure this out, I thought I might ask if anyone has, or knows of, a straightforwardly cogent and/or self-explanatory example of a URLconf that defines a nested namespace, that they could share. 我想,如果有人拥有或知道一个直接有说服力和/或不言自明的URLconf定义嵌套命名空间的例子,我可能会问他们可以分享这些尝试。

Specifically I am curious about the nested parts that prefix the view: need they all be installed Django apps? 具体来说,我很好奇视图前缀的嵌套部分:需要它们安装Django应用程序吗?

†) For the curious, here's a (probably somewhat inscrutable) example: http://imgur.com/NDn9H . †)对于好奇,这是一个(可能有点难以理解)的例子: http//imgur.com/NDn9H I was trying to get the URLs printed out in red and green at the bottom to be named testapp:views:<viewname> instead of just testapp:<viewname> . 我试图将底部以红色和绿色打印的URL命名为testapp:views:<viewname>而不仅仅是testapp:<viewname>

It works rather intuitively. 它的工作非常直观。 include a urlconf that has yet another namespaced include will result in nested namespaces. 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/

It's a great way to keep urls organized. 这是保持网址组织的好方法。 I suppose the best advice I can give is to remember that include can take a patterns object directly (as in my example) which lets you use a single urls.py and split views into useful namespaces without having to create multiple urls files. 我想我能给出的最好建议是记住include可以直接采用patterns对象(如我的例子中所示),它允许您使用单个urls.py并将视图拆分为有用的命名空间,而无需创建多个url文件。

While Yuji's answer is correct, note that django.conf.urls.patterns no longer exists (since Django 1.10) and plain lists are used instead. 虽然Yuji的答案是正确的,但请注意django.conf.urls.patterns不再存在(因为Django 1.10)而使用普通列表。

The same example urls.py should now be like this: 同样的例子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'),
]   

And still used like: 仍然使用像:

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

.
UPDATE: Django 2.0 introduced two relevant changes. 更新: Django 2.0引入了两个相关的更改。 First, the urls() function is now in django.urls , so the first line of the urls.py example above would be: 首先, urls()函数现在位于django.urls ,因此上面urls.py示例的第一行将是:

from django.urls import include, url

Second, it introduce the path() function as a simpler alternative for paths that don't require a regular expression. 其次,它引入了path()函数作为不需要正则表达式的路径的更简单的替代方法。 Using that, the example urls.py would be like this: 使用它,示例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' 似乎没有任何模式 - django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.urls' does not appear to have any patterns in it 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 django.core.exceptions.ImproperlyConfigured:包含的 URLconf“notes.urls”似乎没有任何模式 - django.core.exceptions.ImproperlyConfigured: The included URLconf 'notes.urls' does not appear to have any patterns in it 包含的 URLconf 'appName.urls' 中似乎没有任何模式 - The included URLconf 'appName.urls' does not appear to have any patterns in it 包含的 URLconf 'myapp.urls' 中似乎没有任何模式 - The included URLconf 'myapp.urls' does not appear to have any patterns in it Django 说配置不当:包含的 URLconf 中似乎没有任何模式 - Django says ImproperlyConfigured: The included URLconf does not appear to have any patterns in it 包含的 URLconf 中似乎没有任何模式。 错误Django - The included URLconf does not appear to have any patterns in it. Error in Django Django1.11-URLconf似乎没有任何模式 - Django1.11 - URLconf does not appear to have any patterns Django错误“包含的URLconf中似乎没有任何模式” - Django error “The included URLconf does not appear to have any patterns in it” 配置不当:包含的URLconf“buttonpython.urls”似乎没有任何模式 - ImproperlyConfigured: The included URLconf 'buttonpython.urls' does not appear to have any patterns in it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM