1

我正在尝试让 django命名空间 url 解析工作,因为我希望我的老板和他的老板能够看到模板并从一个应用程序中对其进行评论在不同的应用程序中开发实时代码时使用相同的模板。所以如果你去http://localhost:8000/template_test/base你会看到带有假数据的base.html模板,如果你去http://localhost:8000/uar/base你会看到带有(希望是)真实数据的base.html。作为一个额外的复杂因素,页面上有一个链接应该转到 uar.html,其中包含虚假数据或真实数据,具体取决于您访问的是 /template_test/base url 还是 /uar/base url。

所以这里是模板的适当部分:

<li>
  <a href="{% url 'uar:uar' %}">User Access Review</a>
</li>

这是我的项目/urls.py 的适当部分

url(r'^template_test/', include(template_test.urls,
    namespace="uar", app_name="template_test")),

url(r'^uar/', include(uar.urls, namespace="uar", app_name="uar")),

在 template_test/urls.py

urlpatterns = patterns('',
  url(r'^base$', template_test.views.base, name="base"),
  url(r'^uar$', template_test.views.uar_missing, name="uar"),

在 uar/urls.py

urlpatterns = patterns('',
  url(r'^base$', uar.views.base, name="base"),
  url(r'^uar$', uar.views.uar_missing, name="uar"),

模板测试/views.py

def base(request):
    return render(request, "base.html", {"full_name": "Fake User"},
            current_app="template_test")

和 uar/views.py

def base(request):
    return render(request, "base.html", {"full_name": "Paul Tomblin"},
            current_app="uar")

def uar_missing(request):
    return render(request, "uar.html", {}, current_app="uar")

但是尽管我为模板提供了一个应用程序上下文,当 base.html 在任一上下文中呈现时,{% url 'uar:uar' %}模板中的最终都/template_test/uar/在两个上下文中({{full_name}} 具有适当的值,分别是“假用户”或“Paul Tomblin”)。为了使该链接使用当前的应用程序上下文,我必须进行哪些更改?

附加信息 应用程序上下文不适用于反向:

python manage.py shell
Python 2.7.4 (default, Apr 19 2013, 18:28:01) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.urlresolvers import reverse
>>> reverse('uar:uar')
'/template_test/uar'
>>> reverse('uar:uar', current_app='uar')
'/template_test/uar'
>>> reverse('uar:uar', current_app='template_test')
'/template_test/uar'
>>> reverse('uar:uar', current_app='txx')
'/template_test/uar'
4

1 回答 1

0

显然我混淆了“命名空间”和“app_name”。我的 project/urls.py 现在看起来像:

   url(r'^template_test/',
        include(build_urls(template_test.views, 'template_test'),
        namespace="template_test", app_name="uar")),

    url(r'^uar/',
        include(build_urls(uar.views, 'uar'),
        namespace="uar", app_name="uar")),

注意:我已经切换了命名空间和 app_name。

template_test/views.py 有

def base(request):
    return render(request, "base.html", {"full_name": "Fake User"},
            current_app="template_test")

并且 uar/views.py 有

def base(request):
    return render(request, "base.html", {"full_name": "Paul Tomblin"})

注意:我不再在 uar/views.py 中传递 current_app 了。

作为额外的奖励,我还发现当我使用重定向时,我需要使用正确的 current_app 进行“反向”。

于 2013-06-12T20:03:43.320 回答