【问题标题】:Django Form: NoReverseMatchDjango 表单:NoReverseMatch
【发布时间】:2018-01-24 23:29:33
【问题描述】:

出现错误:NoReverseMatch:未找到“post_new”的反向。 'post_new' 不是有效的视图函数或模式名称。

我在 base.html 中的表单:

> <form action="{% url 'post_new' %}" method="post">
>     {% csrf_token %}
>     Name:<br>
>     <input type="text" name="name"><br>
>     Text:<br>
>     <input type="text" name="text">
>     <input type="submit" value="Submit"> 
  </form>

views.py:

def post_new(request):
    posts = Post.objects.all()
    name = request.POST['name']
    print(name)
    return render(request, 'blog/base.html', {'posts': posts})

urls.py:

urlpatterns = [
    url(r'^$', views.base),
    url(r'^post_new/$', views.post_new, name='post_new'),
]

【问题讨论】:

  • 如果将action="{% url 'post_new' %}" 替换为action="." 会发生什么?

标签: python django web django-forms


【解决方案1】:

您的 Django 项目中似乎有一个名为 blog 的应用程序。假设是这种情况,您需要使用命名空间。在您的主 urls.py 文件中,您应该有这样的内容:

urlpatterns = [
    url(r'^blog/', include('blog.urls', namespace="blog")),
]

您可以在blog 应用下的urls.py 中保持urlpatterns 不变。使用此命名空间集,您可以通过执行以下操作在模板中引用 post_new 视图:

<form action="{% url 'blog:post_new' %}" method="post">

这会在 blog 应用程序中查找名为 post_new 的视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2019-03-24
    • 1970-01-01
    • 2017-07-17
    • 2014-02-10
    • 2017-05-21
    相关资源
    最近更新 更多