Ghasem
Ghasem

Reputation: 15573

Reverse for '' with keyword arguments '' not found

I'm using django 2.1 and python 3.6 and I'm running to an issue which seems like other people have ran into in past years.

This is part of my views.py:

def blog_list_by_cat(request, cat_id, cat_name):
    ...

def blog_list_by_genre(request, genre_id, genre_name):
    ...

This is my urls.py:

urlpatterns = [
    path('', views.index, name='index'),
    re_path(r'^blog/(?P<blog_id>\d+)/(?P<slug>[^/]+)/?$', views.single_blog, name='single_blog'),
    re_path(r'^blog-list/(?P<cat_id>\d+)/(?P<cat_name>[^/]+)/?$', views.blog_list_by_cat, name='blog_list_by_cat'),
    path('blog-list/latest/', views.blog_latest, name='blog_latest'),
    re_path(r'^blog-list/genre/(?P<genre_id>\d+)/(?P<genre_name>[^/]+)/?$', views.blog_list_by_genre, name='blog_list_by_genre'),
]

and in my template when I call those links, this one works fine:

{% for cat in cat_list %}
    <a class="dropdown-item" href="{% url 'blog_list_by_cat' cat_id=cat.id cat_name=cat.cat %}">{{ cat.cat }}</a>
{% endfor %}

While this one throw an error in the same template:

{% for genre in genre_list %}
    <li><a class="dropdown-item" href="{% url 'blog_list_by_genre' genre_id=genre.id genre_name=genre.title %}">{{ genre.title }}</a></li>
{% endfor %}    

This is the full error:

Exception Type: NoReverseMatch

Exception Value: Reverse for 'blog_list_by_genre' with keyword arguments '{'genre_id': 5, 'genre_name': 'Action'}' not found. 1 pattern(s) tried: ['blog-list/genre/(?P\d+)/(?P[^/]+)/?$']

As you can see, I'm using named urls and I'm using quotations around the url name and not adding app name in urls. both codes are the same. But why the second one does not work?

Upvotes: 2

Views: 3671

Answers (1)

user9727749
user9727749

Reputation:

Try using a non-greedy qualifier:

(?P<genre_name>.+?)

Sometimes this helps me match urls when the name of my model has a space in it like "Space Needle".

Upvotes: 2

Related Questions