具有以下定义:
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
# Homepage
url(r'^$', projects.homepage, name='homepage'),
url(r'^create_new_project/$', projects.create_new_project),
# Project page
url(r'^(?P<project_path>\w+)/', include('projects.urls')),
]
项目/ urls.py
from . import views as projects
from gpuz import views as gpuz # gpuz as a sample tool
from models import views as models
urlpatterns = [
url(r'^$', projects.projectpage, name='project-page'),
url(r'^gpuz/$', gpuz.page),
url(r'^settings/$', models.settings_new),
]
我可以解析localhost/myproject/
和localhost/myproject/gpuz/
等网址,但通过模板生成网址会给我带来NoReverseMatch错误。
示例:
base.html文件
<div class="navbar-collapse collapse ">
<ul id="menu-top" class="nav navbar-nav navbar-right">
<li><a href="{% url 'homepage' %}" class="navbar-btn-home">Home</a></li>
{% if project %}
<!-- NoReverseMatch -->
<li><a href="{% url 'project-page' %}">{{ project.name }}</a></li>
{% endif %}
{% if project_tools %}
{% for tool in project_tools %}
<!-- Expected URL: /myproject/gpuz/ -->
<li><a href="{% url 'project-page' tool.name %}" class="navbar-btn-{{tool.name}}">{{ tool.name }}</a></li>
{% endfor %}
<li><a href="/settings" class="navbar-btn-settings">Settings</a></li>
{% endif %}
</ul>
</div>
我在这里遵循这个例子:https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url但它似乎对我不起作用,我无法弄清楚出了什么问题。我的代码中没有使用reverse()
。
错误讯息:
NoReverseMatch
{% if project %}
<li><a href="{% url 'project-page' %}">{{ project.name }}</a></li>
{% endif %}
Exception Type: NoReverseMatch
Exception Value: Reverse for 'project-page' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
临时解决方法
我一直在花费太多时间来解决这个问题,因此我目前的解决方法是将变量链接起来以形成伪硬编码的URL,例如href="/{{ project.url_path }}/{{ tool.name }}/"
。
答案 0 :(得分:0)
试试这个:
<li><a href="{% url 'projects:project-page' %}">{{ project.name }}</a></li>
答案 1 :(得分:0)
url(r'^(?P<project_path>\w+)/', include('projects.urls'))
如果你把这个url放在main urls.py中,你需要从Html页面传递项目路径,否则它会引发异常,就像没有反向匹配一样,所以正确的方法是
主要urls.py
url(r'^$', include('projects.urls')),
项目urls.py
添加项目路径网址(注意:从模板中传递项目路径,如{% url 'project-page' project.path %}
)