mysite.urls 中定义的 URLconf 中的 Django 项目错误,无法发现错误
Django Project -error in the URLconf defined in mysite.urls, cannot spot error
我看过以前的答案(很多是针对旧版本的 Django 的,但没有帮助),但无法在我的代码中发现错误。我在 运行 服务器上收到 'page not found' 错误,然后单击表单的 'submit' 按钮。
问题似乎出在 重定向 上。我不太明白错误消息(见下文)或它是如何工作的,所以解释会有所帮助。
The current path, addMessage/worldguestbook/worldguestbook.html
相关views.py代码和函数**
def addMessage(request):
new_item =GuestBookItem(content=request.POST['content'])
new_item.save()
return HttpResponseRedirect('worldguestbook/worldguestbook.html')
表格(在html)
<form action="/addMessage/" method="post">{% csrf_token %}
<input type="text" name="content"/>
<input type="submit" value="Add"/>
</form>
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('worldguestbook/',worldguestbookView),
path('login/',loginView),
path('addMessage/',addMessage),
]
错误 1
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/addMessage/worldguestbook/worldguestbook.html
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
worldguestbook/
login/
addMessage/
The current path, addMessage/worldguestbook/worldguestbook.html, didn't match any of these.
注意:内容确实提交了,但是没有正确重定向。
您混淆了重定向和呈现。您渲染了一个模板,但您需要重定向到 URL。 URL 您想重定向到什么?正如错误指出的那样,它必须是 urls.py.
中的其中一个
例如:
return HttpResponseRedirect('/worldguestbook/')
更好的是,您应该给 URL 模式名称并将这些名称与 reverse
或 redirect
快捷方式一起使用。
我看过以前的答案(很多是针对旧版本的 Django 的,但没有帮助),但无法在我的代码中发现错误。我在 运行 服务器上收到 'page not found' 错误,然后单击表单的 'submit' 按钮。
问题似乎出在 重定向 上。我不太明白错误消息(见下文)或它是如何工作的,所以解释会有所帮助。
The current path, addMessage/worldguestbook/worldguestbook.html
相关views.py代码和函数**
def addMessage(request):
new_item =GuestBookItem(content=request.POST['content'])
new_item.save()
return HttpResponseRedirect('worldguestbook/worldguestbook.html')
表格(在html)
<form action="/addMessage/" method="post">{% csrf_token %}
<input type="text" name="content"/>
<input type="submit" value="Add"/>
</form>
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('worldguestbook/',worldguestbookView),
path('login/',loginView),
path('addMessage/',addMessage),
]
错误 1
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/addMessage/worldguestbook/worldguestbook.html
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
worldguestbook/
login/
addMessage/
The current path, addMessage/worldguestbook/worldguestbook.html, didn't match any of these.
注意:内容确实提交了,但是没有正确重定向。
您混淆了重定向和呈现。您渲染了一个模板,但您需要重定向到 URL。 URL 您想重定向到什么?正如错误指出的那样,它必须是 urls.py.
中的其中一个例如:
return HttpResponseRedirect('/worldguestbook/')
更好的是,您应该给 URL 模式名称并将这些名称与 reverse
或 redirect
快捷方式一起使用。