Roman
Roman

Reputation: 141

NoReverseMatch with keyword arguments not found when the keyword arguments match

I'm getting the error:

Reverse for 'search_blog' with keyword arguments '{'search_terms': ''}' not found. 1 pattern(s) tried: ['blog/search/(?P[^/]+)/$']

So, my arguments match and yet I'm getting a NoReverseMatch...

I've tried removing the <str:search_terms> pattern from the 'search_blog' path and excluded the kwargs parameter from my reverse call, and that worked. So, the problem must lie solely in the url pattern. I tried renaming the pattern to 'terms' but got the same error:

Reverse for 'search_blog' with keyword arguments '{'terms': ''}' not found. 1 pattern(s) tried: ['blog/search/(?P[^/]+)/$']

Here are the relevant snippets:

urls.py

path('search/', views.nav_search_input, name='nav_search_input'),
path('search/<str:search_terms>/', views.search_blog, name='search_blog'),

views.py

def nav_search_input(request):
    if request.method == 'POST':
        form = SearchBlog(request.POST)

        if form.is_valid():
            return HttpResponseRedirect(reverse('search_blog', kwargs={'search_terms': form.cleaned_data['search_terms']}))

    else:
        form = SearchBlog()

    context = {
        'form': form
    }

    return render(request, 'index.html', context)


def search_blog(request, search_terms=''):
    posts = Post.objects.all()
    form = SearchBlog()

    if form.is_valid():
        posts = Post.objects.all().filter(title__contains=search_terms)

    context = {
        'form': form,
        'posts': posts
    }

    return render(request, 'blog/search_blog.html', context)

and the forms.py in case you need it

class SearchBlog(forms.Form):
    search_terms = forms.CharField(required=False)

    def clean_search_terms(self):
        search_terms = self.cleaned_data['search_terms']
        return search_terms

The nav_search_input view lets me use a form in the base.html so that I can search the site from any page in the nav. The form input data should then go through nav_search_input to the search_blog view where the results are displayed. However I just get the error when I search from the nav form.

Upvotes: 1

Views: 985

Answers (1)

Roman
Roman

Reputation: 141

From Roman to Roman: please check your base template. Check every file that has to do with the search_blog form. The error may show up somewhere you don't expect (clearly from your not posting a snippet from the template).

Add a name to the character field matching the form input field variable name: <input type="search" name="search_terms">. (I didn't want to delete this question so I answered it myself, I wish I could close this question.)

Upvotes: 2

Related Questions