Home > Software engineering >  NoReverseMatch problem with UpdateView class in Django
NoReverseMatch problem with UpdateView class in Django

Time:08-30

I am trying to create an update view in django, inheriting UpdateView. My view looks like this:

class UpdateStudentView(UpdateView):
    model = Student
    form_class = StudentForm
    template_name = "students/students_update.html"
    success_url = reverse_lazy("students:students")

This view takes Student`s primary key as an argument from url

    path("update/<uuid:pk>/", UpdateStudentView.as_view(), name="update_student"),

And here is the template, which should take this primary_key from url and pass it to view.

{% block content %}
        <form action="{% url "students:update_student" pk %}" method="post"> {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>
        </form>
{% endblock content %}

However, it doesn`t work and throws a NoReverseMatch:

NoReverseMatch at /students/update/primary_key_here/
Reverse for 'update_student' with arguments '('',)' not found. 1 pattern(s) tried: ['students/update/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/\\Z']

Could you please explain me why does this happen and how can I avoid this error?

Please don`t tell me about using pk_url_kwarg = 'pk', as it is 'pk' by default

Thanks in advance!

CodePudding user response:

This:

path("update/<uuid:pk>/", UpdateStudentView.as_view(), name="update_student"),

means, that the VIEW is accepting pk kwarg, not the template. In template it so far is empty unless you put it in context (that is why Django search urls with empty argument so far). In update action you don't have to put action="" inside form, because submit button will do automatically what you need from UpdateView (because you have success_url set).

PS you should use object.pk or student.pk if you have context_object_name="student" in your view.

  • Related