1

I am passing 2 variables in the URL foo, bar. The variable bar has a multiple words with spaces between it. On the basis of foo and bar the content of the template is rendered. Whenever bar has a space in between the words my url handler gives a 404.

example: localhost/post/foo/ba r/ results in a 404

urls.py

urlpatterns = [
    re_path('post/<slug:foo>/<slug:bar>/', post),
]

views.py

def post(request, foo, bar):
    query = Blog.objects.all().filter(category=foo, title=bar)
    return render(request, 'blog/post.html',
                  {'blog': query, 'cat': foo, 'tit': bar})

post.html

{% for i in blog %}
    {{ i.content }}
{% endfor %}
5
  • Can you try logging the foo and bar before query ? Commented Jun 11, 2018 at 9:23
  • I don't understand, logging as in how? @Umair Commented Jun 11, 2018 at 9:25
  • try print(foo) print(bar) and check whats the output in console [assuming you're using python3] Commented Jun 11, 2018 at 9:26
  • I already am doing that in my actual code, this is just a stripped down version I've posted. My DB Model is setup this way that bar will contain multiple words and spaces in between them Commented Jun 11, 2018 at 9:29
  • What's being printed there ? Commented Jun 11, 2018 at 9:33

1 Answer 1

2

You can allow spaces along with other characters using regex.

re_path(r'^post/(?P<foo>[\w|\W]+)/(?P<bar>[\w|\W]+)/$', post)
Sign up to request clarification or add additional context in comments.

1 Comment

I am glad that it helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.