简体   繁体   中英

Django Form: NoReverseMatch

Getting an error: NoReverseMatch: Reverse for 'post_new' not found. 'post_new' is not a valid view function or pattern name.

my form in 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'),
]

It seems that you might have an app in your Django project called blog . Assuming this is the case, you need to use namespaces. In your main urls.py file, you should have something like this:

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

You can keep the urlpatterns the same in the urls.py under your blog app. With this namespace set you can reference the post_new view in your templates by doing the following:

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

This looks for the view called post_new in the blog app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM