简体   繁体   中英

Django NoReverseMatch and POST URL error

I am facing 2 issues NoReverseMatch and APPEND_SLASH .

Issue #1. APPEND_SLASH

Detail.html

<form action="update-entry" method="post">
/* if I add '/' at the end of update-entry, it works fine. */
{% csrf_token %}
{{ form }}
<input type="submit" value="Edit">
</form>

When I click on the Edit button, I get the error below,

 You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/genericviews/1/update- entry/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. 

This is the URL generated:

http://127.0.0.1:8000/genericviews/1/update-entry

I know URL should end with '/'.

urls.py

urlpatterns = [

url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailsView.as_view(), name='detail'),
url(r'^makeentry$', views.makeentry, name='makeentry'),
url(r'^static/$', views.StaticView.as_view()),


url(r'^new-entry/$', views.MakeEntryView.as_view(), name='new-entry'),

url(r'^(?P<pk>[0-9]+)/update-entry/$', views.UpdateEntryView.as_view(), name='update-entry'),


]

My confusion is why URL is not generating '/' at the end. Above URL pattern seems correct to me.

Issue #2 NoReverseMatch

When I try to change the hardcoded URL, I get the error below,

NoReverseMatch at /genericviews/1/
Reverse for 'update-entry' with arguments '()' and keyword arguments '{}' 
not found. 1 pattern(s) tried: ['genericviews/(?P<pk>[0-9]+)/update-
entry/$']

Detail.html

<form action="{% url 'genericviews:update-entry' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Delete Product"> 
</form>

tried link as well,

{#<a href="{% url 'genericviews:update-entry' %}">Edit</a>#}

When I click on any item from the page http://127.0.0.1:8000/genericviews/ , it takes me to the URL http://127.0.0.1:8000/genericviews/1/ And this is where it shows error.

I checked other answers, however, couldn't get it to work.

Any help would be appreciated.

It's not adding a slash because you haven't asked it to. You've hard-coded the relative URL of "update-entry", so that's what it will use.

When you do try and use the url tag, you get the error because you haven't passed the arguments it needs to generate that URL. Assuming you have the object in your template context as object , you would do:

{% url 'genericviews:update-entry' pk=object.pk %}

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