我有app_main / templates / app / detail.html:
{% for i in user_items %}
<li><a href="{% url 'app_main:update_last_clicked' username=username url=i.url %}">{{ i }}</a></li>
{% endfor %}
我有app_main / urls.py:
url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$', views.update_last_clicked, name='update_last_clicked'),
我在app_main / views.py:
def update_last_clicked(request, username, url):
user = get_object_or_404(User, username=username)
user.item_set.get(url=url).last_clicked += 1
return HttpResponseRedirect(url)
我得到NoReverseMatch错误如下:
NoReverseMatch at /app_main/u/florin/
Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$']
Request Method: GET
Request URL: http://127.0.0.1:8080/app_main/u/florin/
Django Version: 1.11.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$']
Exception Location: /Users/f/Desktop/django/lib/python2.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497
Python可执行文件:/ Users / f / Desktop / django / bin / python Python版本:2.7.10
更多:
In template /Users/f/Desktop/django/app/app_main/templates/app_main/detail.html, error at line 5
Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$']
我不明白发生了什么:我只想更新单击的项目对象中的属性,但添加了此代码后,当我转到detail.html视图时,它会给我这个错误, urlpattern是url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/$', views.detail, name='detail'),
app_main / urls.py中的完整urlpatterns是:
app_name = 'app_main'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/$', views.detail, name='detail'),
url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/add_item/$', views.add_item, name='add_item'),
url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$', views.update_last_clicked, name='update_last_clicked'),
]
作为参考,app / urls.py有url(r'^app_main/', include('app_main.urls')),
我基本上想要将单击的项目传递给没有表单的视图。我想,因为我只需要传递item的url属性,我可以将它附加到当前url以传递它。我错了吗?我是否必须使用AJAX调用或表单?
FIX:我一直在改变事情,只是将url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$', views.update_last_clicked, name='update_last_clicked'),
更改为url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>.*)/$', views.update_last_clicked, name='update_last_clicked'),
。有没有人理解为什么简单地取出分组括号会改变这个?
答案 0 :(得分:0)
您必须为应用程序指定命名空间 例如 -
url(r'^app_main/', include('app_main.urls', namespace='app_main'))
类似,对于您要根据应用和网址名称进行逆转的所有其他应用。
你也可以这样提及app_name
中的app_main/urls.py
-
app_name = 'app_main'
urlpatterns = [...]
参考:https://docs.djangoproject.com/en/1.11/topics/http/urls/#reversing-namespaced-urls