Django 1.8 / Python 3.4
我有一个website.html,显示我的数据库中的条目,每个条目都由其ID标识。现在,在每个显示的条目的末尾,我有一个指向"编辑"的链接。查看,看起来像这样:
<td><a href="{% url 'edit' object.id %}">edit</a></td>
链接工作正常,可以看到正确的视图:
def edit(request, object_id):
在views.py
中实施。有些代码也正确执行,在视图的最后一行我有:
return redirect('website.html')
显然,在编辑了所选条目后,我希望我的website.html中已编辑的条目再次显示在浏览器中:127.0.0.1:8000/website/
。但是,发生的情况是我收到Page not found (404)
错误,其中包含以下信息:
Requested URL 127.0.0.1:8000/website/2/website.html
&#34; 2&#34;这是条目的ID。
也许我对重定向如何工作有错误的想法,但我假设不会从url.py调用相应的视图网址,而是打开redirect()
函数中提供的网址?!
但是,这个网址会被附加到视图的网址上!
这是我的urls.py
:
from django.conf.urls import include, url
from django.contrib import admin
from www.list.views import website, edit
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^website/$', website, name="website"),
url(r'^website/(?P<object_id>\d+)/$', edit, name="edit"),
]
我非常确定第三个网址条目是导致问题但我完全不知道如何更改它以使重定向工作。此外,编辑视图没有实际的网站(模板),但我应该为它提供一个URL,所以这是我能想到的最好的。
这应该是这样的:点击&#34;编辑&#34;在website.html上的链接,正在执行编辑视图中的代码,之后,再次显示包含数据库条目更改的website.html。
^^怎么做到这一点?任何帮助表示赞赏!
答案 0 :(得分:4)
重定向使用name
或绝对URL。您应该使用网址的名称:
return redirect('website') # since name="website"
或绝对网址,例如:
return redirect('/website/')
答案 1 :(得分:2)
您可以使用反向功能代替重定向
from django.core.urlresolvers import reverse return reverse('website')
答案 2 :(得分:2)
我发现了错误和解决方案:
在编辑视图结束时,写入&#34;返回重定向(&#39;网站&#39;)&#34;是正确的。但是,就像我假设的那样,urls.py中的编辑URL是错误的。
而不是
url(r'^website/(?P<object_id>\d+)/$', edit, name="edit"),
它应该只是
url(r'^(?P<object_id>\d+)/$', edit, name="edit"),
尽管如此,谢谢!