Home > database >  NoReverseMatch: Redirect to a new page in Django with a query from a template
NoReverseMatch: Redirect to a new page in Django with a query from a template

Time:04-28

I want to redirect from inside my HTML Template to a new page and also pass a query to that page as a GET request query.

The HTML code looks like this.

<th scope="row">{{ forloop.counter }}</th>
<td>{{ project.article_title }}</td>
<td>{{ project.target_language }}</td>
<td> <a href="{% url 'translation/{{project.id}}/' %}" >View Project</a></td>

This doesn't redirect and I get the following error.

NoReverseMatch at /manager/
Reverse for 'translation/{{project.id}}/' not found. 'translation/{{project.id}}/' is not a valid view function or pattern name.

My URL pattern looks like this

urlpatterns = [
    path('', views.project_input_view, name='main'),
    path('login/', views.login_user, name='login'),
    # path('register/', views.register_user, name='register'),
    path('translation/<str:pk>/', views.translation_view, name='translation'),
    path('manager/', views.manager_view, name='manager_dashboard'),
    path('annotator/', views.annot_dashboard_view, name='annot_dashboard'),
]

However, if I write the following then it works.

<th scope="row">{{ forloop.counter }}</th>
<td>{{ project.article_title }}</td>
<td>{{ project.target_language }}</td>
<td> <a href="{% url 'main' %}" >View Project</a></td>

but I want to redirect to the translation page along with the query. How can I achieve that?

CodePudding user response:

This should work provided you are redirecting to a detail class-based view from a list class-based view:

{% url 'translation' project.id %}

An example for function-based views:

urls.py:

from .views import detail_view

urlpatterns = [
    path('<id>', detail_view ),
]

views.py:

from django.shortcuts import render


# relative import of forms

from .models import GeeksModel
# pass id attribute from urls

def detail_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}

    # add the dictionary during initialization
    context["data"] = GeeksModel.objects.get(id = id)
     
    return render(request, "detail_view.html", context)
  • Related