从 Django 中的模板访问命名视图
Accessing a named view from a template in django
假设我有两个应用 AppA 和 AppB
|_AppB
| |_urls.py # url(r'^create/', views.user_profile, name="name_user_profile"),
|
|_AppA
|_urls.py
|_templates
|_file.html
现在 file.html 我有这样的东西
{% block content %}
Success !!!
goto <a href={% url `name_user_profile` % }> Manage Profile </a>
{% endblock %}
但是name_user_profile无法识别?我需要做些什么才能让它被识别吗?
更新:
这是我目前所做的
在我的主应用程序 urls.py 中(带有 settings.py 的应用程序)。我添加了以下内容
url(r'^profile/', include("UserProfile.urls" , namespace="UserProfile" , app_name="UserProfile")),
现在在视图所在的我的 UserProfile 应用程序中,我有这个
urlpatterns = [
url(r'^$', views.user_profile, name="name_user_profile"),
]
需要调用该视图的模板位于第三个应用程序中
已调用的帐户具有此
goto <a href={% url 'UserProfile:name_user_profile' % }> Manage Profile </a>
但这似乎不起作用
由于您的应用引用了不同的 urls.py
文件,为了使用命名 URL,您需要访问每个具有自己命名空间的文件。
Check out the example in the docs here。有一个 urls.py
文件使用 include('polls.urls')
。然后,在实际的投票应用程序中,有几个命名的 URL,index
和 detail
。由于它们位于应用程序内部,因此可以分别使用它们的命名空间访问这些 url - {% url 'polls:index' %}
和 {% urls 'polls:detail' %}
。
如果您在 Django 1.9 之前工作,则必须在 include
语句之后专门提供 namespace
参数。从 1.9 开始,当您 include
来自应用程序的 urls.py 文件时,Django 会自动使用应用程序名称作为命名空间。
假设我有两个应用 AppA 和 AppB
|_AppB
| |_urls.py # url(r'^create/', views.user_profile, name="name_user_profile"),
|
|_AppA
|_urls.py
|_templates
|_file.html
现在 file.html 我有这样的东西
{% block content %}
Success !!!
goto <a href={% url `name_user_profile` % }> Manage Profile </a>
{% endblock %}
但是name_user_profile无法识别?我需要做些什么才能让它被识别吗?
更新:
这是我目前所做的
在我的主应用程序 urls.py 中(带有 settings.py 的应用程序)。我添加了以下内容
url(r'^profile/', include("UserProfile.urls" , namespace="UserProfile" , app_name="UserProfile")),
现在在视图所在的我的 UserProfile 应用程序中,我有这个
urlpatterns = [
url(r'^$', views.user_profile, name="name_user_profile"),
]
需要调用该视图的模板位于第三个应用程序中 已调用的帐户具有此
goto <a href={% url 'UserProfile:name_user_profile' % }> Manage Profile </a>
但这似乎不起作用
由于您的应用引用了不同的 urls.py
文件,为了使用命名 URL,您需要访问每个具有自己命名空间的文件。
Check out the example in the docs here。有一个 urls.py
文件使用 include('polls.urls')
。然后,在实际的投票应用程序中,有几个命名的 URL,index
和 detail
。由于它们位于应用程序内部,因此可以分别使用它们的命名空间访问这些 url - {% url 'polls:index' %}
和 {% urls 'polls:detail' %}
。
如果您在 Django 1.9 之前工作,则必须在 include
语句之后专门提供 namespace
参数。从 1.9 开始,当您 include
来自应用程序的 urls.py 文件时,Django 会自动使用应用程序名称作为命名空间。