Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NoReverseMatch Error during template rendering

I have this url that causes the error

<a href="{% url 'page-two' item_1 item_2 %}">

The url should be rendered as /pages/36/some-story

urls.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

urlpatterns = [
        path('pages/<slug:slug>', views.PageOneView.as_view(), name='page-one'),
        path('pages/<slug:slug_1>/slug:slug_2>', views.PageTwoView.as_view(), name='page-two'),
    ]

views.py

class PageOneView(View):
    def get(self, request, slug):
        run = Pages.objects.get(id=slug)

        item_1 = 36
        item_2 = 'some-story'

        context = {
            'item_1': item_1,
            'item_2': item_2,
        }

        return render(request, "pages/page_1.html", context)


class PageTwoView(View):
    def get(self, request, slug_1, slug_2)
        
        context = {}

        return render(request, "pages/page_2.html", context)

The trackback says:

Reverse for 'page-two' with arguments '('36', 'some-story')' not found.

It seems like the url get’s rendered correctly because I see the values I expected. But I still can’t figure out where this error is coming from. What have I done wrong?

>Solution :

The error message you’re encountering indicates that there is an issue with the reverse resolution of the URL pattern in your Django application. The error message specifically mentions that it cannot find a reverse for 'page-two' with the provided arguments ('36', 'some-story').

Upon inspecting your urls.py file, it appears that there is a typo in the URL pattern definition for PageTwoView. The second part of the URL pattern is missing a leading < symbol before slug:slug_2.

To fix the issue, update your urls.py file as follows:

urlpatterns = [
    path('pages/<slug:slug>/', views.PageOneView.as_view(), name='page-one'),
    path('pages/<slug:slug_1>/<slug:slug_2>/', views.PageTwoView.as_view(), name='page-two'),
]

By adding the missing < symbol before slug:slug_2, you define two separate URL parameters (slug_1 and slug_2) for the PageTwoView view.

After making this change, the reverse resolution for the URL with the provided arguments should work correctly, and the error you mentioned should no longer occur.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading