Django url pattern - string parameter

Viewed 127912

Django url pattern that have a number parameter is:

url(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail')

What will be the correct syntax if my poll_id is not a number but a string of character?

7 Answers

In newer versions of Django such as 2.1 you can use

path('polls/<str:poll_id>', views.polls_detail)

as given here Django URL dispatcher

def polls_detail(request,poll_id):
#process your request here

From Django 2.0 onward, path has been introduced. path does not take reg ex in urls, hence it is meant to be a simplified version of the older url

From 2.0 onward you can use path instead like below :

path('polls/<poll_id>', views.polls_detail)

string path parameters need not be explicitly specified, as default data type for path parameters is string itself.

Ref : https://docs.djangoproject.com/en/2.0/releases/2.0/#whats-new-2-0

In case your angle-bracket argument is a path, i.e. contains "/", you'll have to use path:.

Example:
path('section/<path:some_path>,app.views.some_view,name='some_name')

Source: https://docs.djangoproject.com/en/4.0/topics/http/urls/#path-converters

(EDITED)
"str - Matches any non-empty string, EXCLUDING the path separator, '/'. This is the default if a converter isn’t included in the expression.

slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.

path - Matches any non-empty string, INCLUDING the path separator, '/'. This allows you to match against a complete URL path rather than a segment of a URL path as with str."

Related