Skip to content
Advertisement

NoReverseMatch as consequence of a form action

This is my urls.py:

from django.urls import path

from . import views

urlpatterns = [
    path("", views.rando, name="rando"),
    path("wiki", views.index, name="index"),
    path("create", views.create, name="create"),
    path("wiki/<str:title>", views.title, name="title"),
    path("wiki/<str:title>/edit", views.edit, name="edit"),
]

This is my views.py:

def edit(request, title):
    if request.method=="POST":
        content = request.POST.get("content")
        util.save_entry(title, content)
        return redirect(f'/wiki/{title}')
    elif request.method=="GET":
        if title in util.list_entries():
            ge = util.get_entry(title)
            return render(request, "encyclopedia/edit.html", {
                "title": title,
                "ge": ge
            })
        else:
            return render(request, "encyclopedia/error.html")

This is what I want to render (edit.html):

{% block body %}
    <h1>Edit {{title}}</h1>

    <form action="{% url 'edit' %}" method="post">
        {% csrf_token %} 
        <textarea id="ctnt" name="content">{{ge}}</textarea>
        <br>
        <input type="submit" value="Submit">
    </form>



{% endblock %}

When I want to send the form above with the current action it gives me: NoReverseMatch at /wiki/CSS/edit but when I remove action it doesn’t display any error. Could you please tell me why this happens?

Advertisement

Answer

reverse method search for view that naming space. After that it tries to pass needed variables, but you didn’t provide any with {% url 'edit' %}. It should be {% url 'name' first_argument second_argument etc. %}, so in your case: {% url 'edit' title %}.

But as I can see your view, it’s actually pointless to do such action (cause you have redirect in if request.method=="POST" part), and by default try not to do that. It’s good practice to have such backend behaviour directly in your views.py files.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement