【问题标题】:Django Project -error in the URLconf defined in mysite.urls, cannot spot errorDjango Project -mysite.urls 中定义的 URLconf 中的错误,无法发现错误
【发布时间】:2019-09-15 06:06:51
【问题描述】:

我查看了以前的答案(许多是针对旧版本的 Django 的,没有帮助),但无法在我的代码中发现错误。我在运行服务器并单击表单的“提交”按钮时收到“找不到页面”错误。

问题似乎是重定向。我不太了解错误消息(见下文)或它的工作原理,因此解释一下会有所帮助。

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.

注意:内容实际已提交,但未正确重定向。

【问题讨论】:

    标签: django forms url redirect config


    【解决方案1】:

    您将重定向与渲染混淆了。您呈现一个模板,但您需要重定向到一个 URL。您要重定向到哪个 URL?正如错误指出的那样,它必须是您的 urls.py 中的一个。

    例如:

    return HttpResponseRedirect('/worldguestbook/')
    

    更好的是,您应该为您的 URL 模式命名并将这些名称与 reverseredirect 快​​捷方式一起使用。

    【讨论】:

    • Daniel - 非常感谢您的快速回复,是的,您说得对,我将渲染与重定向混淆了 - 从第一个视图复制代码。所以,你的建议有效!你能解释一下为什么两边的斜线 - 我不明白。
    • 另外,你看起来是个 Django 天才。没有人能完全回答这个问题:stackoverflow.com/questions/55658454/…
    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 2011-08-26
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 2022-11-16
    相关资源
    最近更新 更多