Search code examples
djangopython-3.xdjango-viewsurl-pattern

Why isn't variable caught in django url being passed to view as a string?


Am trying to catch a variable in a url in my urls.py file, then pass it to a function in my views file, where I want to use it as a string:

# urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^posts/(?P<title>)', views.blog_ronn_post, name='blog_ronn_post'),
]

# views.py
from django.http import HttpResponse

def blog_ronn_post(request, title):
    html = "<html><body>This is the page for the blog titled: {s} </body></html>".format(title)
    return HttpResponse(html)

However this doesn't work. In my development browser the html shows up, but displays nothing after the final colon. I don't think there is a problem with my Python 3 syntax as if I try to use a string in the format parentheses, eg:

 html = "<html><body>This is the page for the blog titled: {s} </body></html>".format('Title 1')

it works, displaying " ... titled: Title 1". So why doesn't it pass my title string? I understood it that title is passed from url to views as a string, so there should be no problem. New to django so apologies if I'm making an obvious mistake.


Solution

  • Because you haven't given it anything to match.

    r'^posts/(?P<title>\w+)$'